More Next.js answers

by Danny
Published 3 min read

Add an error.tsx Client Component to a route segment to catch runtime errors and show a fallback with a retry button. Use global-error.tsx for errors in the root layout.

The short answer

#

Add an error.tsx file next to the page.tsx you want to protect. It must be a Client Component. When anything inside that segment throws while rendering, Next.js shows this component instead of crashing the whole page, and the rest of the layout stays usable.


_11
// app/dashboard/error.tsx
_11
'use client';
_11
_11
export default function Error({ error, retry }: { error: unknown; retry: () => void }) {
_11
return (
_11
<div role="alert">
_11
<h2>Something went wrong loading your dashboard.</h2>
_11
<button onClick={() => retry()}>Try again</button>
_11
</div>
_11
);
_11
}

Why it happens

#

error.tsx is a React error boundary that Next.js wires up for you. It wraps the segment's page.tsx, loading.tsx, not-found.tsx and any nested layouts. When a Server Component throws, for example because a database call fails, the error travels to the nearest boundary above it and the fallback renders in its place.

Error boundaries rely on React state, which is why the file needs 'use client'. Errors from Server Components reach the browser with the message removed in production, so you do not leak internal details. You get a generic message and an error.digest hash instead, which matches the entry in your server logs.

The props have changed recently. retry became stable in Next.js 16.3 and is now the recommended way to recover: it fetches the segment again and re-renders it. Next.js 16.2 called it unstable_retry. Older versions only offer reset, which clears the error but does not fetch fresh data, so it rarely helps when a server request failed. reset still exists for cases where you only want to re-render.

How to fix it

#

Log the error and show a useful message

The error prop is typed as unknown, because a Client Component can throw anything. Narrow it before reading properties.


_19
'use client';
_19
_19
import { useEffect } from 'react';
_19
_19
export default function Error({ error, retry }: { error: unknown; retry: () => void }) {
_19
useEffect(() => {
_19
reportError(error); // your error tracking service
_19
}, [error]);
_19
_19
const digest = error instanceof Error && 'digest' in error ? String(error.digest) : undefined;
_19
_19
return (
_19
<div role="alert">
_19
<h2>We could not load this page.</h2>
_19
{digest && <p>Reference: {digest}</p>}
_19
<button onClick={() => retry()}>Try again</button>
_19
</div>
_19
);
_19
}

Showing the digest gives support staff something to search for in the logs.

Place boundaries where failure should stay contained

A boundary only covers its own folder and below. Put one in each area that can fail on its own, such as app/dashboard/error.tsx and app/settings/error.tsx, so a broken dashboard widget does not take down settings. The shared navigation in the parent layout keeps working.

Catch errors in the root layout with global-error.tsx

error.tsx does not catch errors thrown by the layout.tsx in the same folder, because that layout sits outside the boundary. For the root layout, add app/global-error.tsx. It replaces the whole document, so it must render its own <html> and <body>, and it does not get your global styles or metadata exports.


_14
// app/global-error.tsx
_14
'use client';
_14
_14
export default function GlobalError({ retry }: { error: unknown; retry: () => void }) {
_14
return (
_14
<html lang="en">
_14
<body>
_14
<title>Something went wrong</title>
_14
<h1>Something went wrong</h1>
_14
<button onClick={() => retry()}>Try again</button>
_14
</body>
_14
</html>
_14
);
_14
}

Handle missing data with notFound()

A record that does not exist is not a crash. Call notFound() from next/navigation and add a not-found.tsx file. That shows a proper 404 instead of the error boundary.


_10
import { notFound } from 'next/navigation';
_10
_10
export default async function Page({ params }: { params: Promise<{ id: string }> }) {
_10
const { id } = await params;
_10
const invoice = await getInvoice(id);
_10
if (!invoice) notFound();
_10
_10
return <h1>Invoice {invoice.number}</h1>;
_10
}

Return expected errors instead of throwing

For validation problems in a form, return an error value from the Server Action and show it with useActionState. Keep error.tsx for things you did not expect.

Common pitfalls

#
  • Forgetting use client. Without it the build fails, because error boundaries must be Client Components.
  • Expecting the same-folder layout to be covered. Move risky code from the layout into the page, or rely on the parent's boundary or global-error.tsx.
  • Expecting event handler errors to be caught. React error boundaries catch errors during rendering, not inside onClick or setTimeout. Use try and catch there and set state.
  • Catching redirect and notFound. Both work by throwing. A broad try and catch around them stops them working, so rethrow or call them outside the block.
  • Relying on error.message in production. Server error messages are hidden on purpose. Use the digest and your server logs.
  • Using reset after a failed fetch. On Next.js 16.3 and later, use retry so the data is fetched again.
#

Was this resource helpful?