Lesson

Next.js Error Handling

10 min reading
Free Course

Next.js Error Handling: Recovering from Runtime Errors and 404s

Next.js error handling isolates unexpected failures inside route segments so one broken widget never crashes the entire application. Special files named error.tsx and not-found.tsx handle runtime crashes and missing records cleanly.

When you place error.tsx inside a folder, Next.js wraps page.tsx in a React Error Boundary. If an exception occurs, users see a helpful recovery screen instead of a blank page.

Catching Route Errors with error.tsx

An error.tsx file must be a Client Component because React Error Boundaries run in the browser. It receives error and a reset function that lets users retry rendering the failed segment.

// app/dashboard/error.tsx
'use client';

import { useEffect } from 'react';

export default function DashboardError({
  error,
  reset,
}: {
  error: Error & { digest?: string };
  reset: () => void;
}) {
  useEffect(() => {
    console.error('Dashboard route error:', error.digest ?? error.message);
  }, [error]);

  return (
    <div className="p-6 bg-red-50 border border-red-200 rounded-lg text-center">
      <h2 className="text-xl font-bold text-red-800">Unable to load dashboard</h2>
      <p className="mt-2 text-sm text-red-700">Please try again or refresh the page.</p>
      <button
        type="button"
        onClick={() => reset()}
        className="mt-4 px-4 py-2 bg-red-600 text-white rounded hover:bg-red-700"
      >
        Try Again
      </button>
    </div>
  );
}

Customizing 404 Pages with not-found.tsx

Create app/not-found.tsx for a site-wide 404 screen, or place not-found.tsx inside a nested folder for section-specific missing pages.

// app/not-found.tsx
import Link from 'next/link';

export default function NotFound() {
  return (
    <div className="flex flex-col items-center justify-center min-h-[60vh] p-6">
      <h2 className="text-3xl font-bold text-gray-800">404 - Page Not Found</h2>
      <p className="mt-2 text-gray-600">The requested resource does not exist.</p>
      <Link href="/" className="mt-6 px-4 py-2 bg-blue-600 text-white rounded">
        Return Home
      </Link>
    </div>
  );
}

Triggering 404s with notFound()

Inside any Server Component, call notFound() from next/navigation when a database lookup or API fetch finds no matching item.

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

export default async function PostPage({
  params,
}: {
  params: Promise<{ id: string }>;
}) {
  const { id } = await params;
  const res = await fetch(`https://api.example.com/posts/${id}`);
  if (res.status === 404) {
    notFound();
  }
  const post = await res.json();

  return (
    <article className="p-6">
      <h2 className="text-2xl font-bold">{post.title}</h2>
      <p className="mt-3 text-gray-700">{post.body}</p>
    </article>
  );
}

Common Mistakes

  • Omitting 'use client' in error.tsx: Next.js throws a build error if error.tsx is left as a Server Component.
  • Trying to catch root layout errors in app/error.tsx: Errors inside app/layout.tsx bubble past app/error.tsx; create app/global-error.tsx with its own <html> and <body> tags to catch root layout crashes.
  • Exposing stack traces in production UI: Log detailed messages to monitoring tools and show friendly plain text to users.

Frequently Asked Questions

Does error.tsx catch 404 missing routes?

No, missing routes and notFound() calls render not-found.tsx, while thrown exceptions render error.tsx.

What is error.digest?

error.digest is a hashed server error ID generated by Next.js so you can match client error screens to server logs without leaking sensitive details.

Can error.tsx recover from a temporary API timeout?

Yes, calling reset() re-renders the route segment and retries its Server Components cleanly.

Save Your Progress

Unlock Your
Full Potential.

Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.

Quick Access With

Enterprise-Grade Security Protocol
Next.js Topic Hub

Stuck on this lesson?

Join our community of senior developers.

Ask in Forum