Back to Next.js tutorials
Advanced13 min read

Error Handling And Recovery

Route-level error boundaries, not-found handling, and stable UX when things go wrong.

error.tsx Boundaries

error.tsx must be a Client Component exporting default function receiving `{ error, reset }`. It catches errors in Server and Client Components in its segment during rendering. Clicking reset re-attempts rendering the segment.

Nest error boundaries per feature — dashboard error does not take down marketing pages. Log error.message and digest to monitoring in useEffect.

  • error.tsx is client component
  • reset() retries segment render
  • Nest boundaries per feature area
'use client';
export default function Error({ error, reset }) {
  return (
    <div>
      <p>Something went wrong</p>
      <button onClick={reset}>Try again</button>
    </div>
  );
}

not-found.tsx

Call `notFound()` from next/navigation in Server Components when data lookup fails — renders nearest not-found.tsx with 404 status. Separate from error.tsx which handles unexpected exceptions.

Global not-found at app level handles unmatched routes. Segment not-found handles missing resources within valid routes (`/users/nonexistent-id`).

  • notFound() for expected missing data
  • 404 status, not 500
  • Different from error.tsx exceptions

global-error.tsx

global-error.tsx wraps root layout failures — must include its own html and body tags since root layout may have crashed. Last resort boundary for catastrophic errors.

Keep global-error minimal and branded. Most errors should be caught by nested error.tsx before reaching this level.

  • Catches root layout failures
  • Must include html and body
  • Last resort boundary

Helpful Error States

Show actionable messages — what failed, what user can do (retry, go home, contact support). Never expose stack traces or internal IDs to users. Map known error types to friendly copy.

For form errors, return field-level messages from Server Actions. For page errors, offer navigation alternatives so users are not stuck on dead ends.

  • Actionable user messages
  • No stack traces to users
  • Navigation alternatives on failures

Production Monitoring

Integrate Sentry or similar with Next.js instrumentation hook. Capture server component errors, client boundary errors, and unhandled rejections with route and user context.

Alert on error rate spikes, not individual errors. Group by digest and route. Tie releases to error timeline for regression identification.

  • instrumentation.ts for monitoring setup
  • Alert on error rate spikes
  • Correlate errors with deployments

Get In Touch


Ready to discuss your next project? Drop me a message.