error.tsx

Add an error.tsx file to catch rendering errors in a segment and show a recovery UI.

Syntaxapp/<segment>/error.tsx (must be 'use client')

An error.tsx file defines an error boundary for its route segment. If a page or its children throw during rendering, Next shows this component instead of crashing the whole app. Error boundaries must be Client Components.

The props

  • error β€” the thrown error object.
  • reset β€” a function that retries rendering the segment.

Example

Example Β· typescript
'use client';

export default function Error({
  error,
  reset,
}: {
  error: Error;
  reset: () => void;
}) {
  return (
    <div>
      <p>Something went wrong: {error.message}</p>
      <button onClick={() => reset()}>Try again</button>
    </div>
  );
}

When to use it

  • A product page wraps its content in an error boundary via error.tsx so a failed API call shows a retry button instead of a crash.
  • A checkout flow shows a user-friendly error message in error.tsx when a payment API throws an exception.
  • A team uses error.tsx to log errors to Sentry via useEffect while still showing a recovery UI to the user.

More examples

Basic error boundary file

error.tsx receives the thrown error and a reset function that re-renders the segment from scratch.

Example Β· ts
'use client'; // error.tsx must be a Client Component
import { useEffect } from 'react';

export default function Error({
  error,
  reset,
}: {
  error: Error;
  reset: () => void;
}) {
  return (
    <div>
      <h2>Something went wrong</h2>
      <p>{error.message}</p>
      <button onClick={reset}>Try again</button>
    </div>
  );
}

Log error to external service

useEffect inside error.tsx runs after render, making it the right place to report errors to monitoring tools.

Example Β· ts
'use client';
import { useEffect } from 'react';

export default function Error({ error, reset }: { error: Error; reset: () => void }) {
  useEffect(() => {
    console.error('Caught error:', error);
    // Sentry.captureException(error);
  }, [error]);

  return (
    <>
      <p>An error occurred.</p>
      <button onClick={reset}>Retry</button>
    </>
  );
}

Error file placement

error.tsx in a segment catches errors from page.tsx in the same folder but not from its parent layout.

Example Β· bash
app/
└── dashboard/
    β”œβ”€β”€ page.tsx     # may throw
    └── error.tsx    # catches errors from page.tsx

Discussion

  • Be the first to comment on this lesson.
error.tsx β€” Next.js | SoundsCode