Error Handling in Next.js: error.tsx, not-found.tsx and global-error

A
Author
15 May, 2026 1 min read 1.41K views

The App Router turns error handling into file conventions. Each route segment can have its own error UI, so one broken widget doesn't take down the whole app.

error.tsx: catch unexpected errors

// app/dashboard/error.tsx
'use client'; // error boundaries must be Client Components

export default function DashboardError({ error, reset }: { error: Error & { digest?: string }; reset: () => void }) {
  return (
    <div role="alert">
      <h2>We couldn't load your dashboard.</h2>
      <button onClick={() => reset()}>Try again</button>
    </div>
  );
}

The boundary wraps the segment's page.tsx and children, but not its own layout.tsx. To catch layout errors, add error.tsx in the parent segment.

In production, server error messages are hidden from the browser; you receive a digest that matches the server logs.

not-found.tsx: missing content

// app/blog/[slug]/page.tsx
import { notFound } from 'next/navigation';

const post = await getPost(slug);
if (!post) notFound(); // renders the nearest not-found.tsx with a 404 status
// app/not-found.tsx
import Link from 'next/link';

export default function NotFound() {
  return (
    <div>
      <h1>Page not found</h1>
      <Link href="/">Back to home</Link>
    </div>
  );
}

global-error.tsx: when the root layout fails

app/global-error.tsx replaces the root layout when it throws, so it must render its own <html> and <body>.

Expected errors are not exceptions

Validation failures and "email already taken" are normal outcomes. Return them from Server Actions as data and show them with useActionState instead of throwing.

if (await emailTaken(email)) return { error: 'That email is already registered.' };

Send unexpected errors to an error tracker (Sentry, OpenTelemetry) from an instrumentation.ts hook or the error boundary.

Was this article helpful?

Comments

No comments yet. Have a question or a tip? Be the first to share it.

Leave a comment

Comments are reviewed before they appear.