Skip to content

Handling Next.js Not Found States and Custom Error Pages

Learn how to build resilient not-found states and error boundaries in Next.js applications to prevent layout breaks and improve user experience.

Published 3min read
Cover illustration for "Handling Next.js Not Found States and Custom Error Pages"
On this page

When a database record goes missing or a user inputs an invalid dynamic segment, Next.js applications need to gracefully display a recovery path instead of crashing or showing a generic white screen. Unhandled runtime exceptions and missing resources frustrate users and degrade the perceived quality of your product. This guide covers how to implement specific not-found pages, global error boundaries, and nested error handlers that preserve your site layout.

Implementing Targeted Not-Found States

Relying on a single global 404 page is rarely sufficient for complex web applications where users expect context-aware messaging. Next.js allows you to scope not-found behavior to specific route segments by creating a not-found.tsx file within any folder in the App Router. When a component calls the notFound() function, the framework renders the nearest matching not-found boundary while preserving the surrounding layout tree.

Consider a dynamic product route at app/products/[id]/page.tsx. If the database query returns null for the requested identifier, you should invoke the utility function immediately rather than rendering partial fallback UI inside your component.

import { notFound } from 'next/navigation';

export default async function ProductPage({ params }: { params: { id: string } }) {
  const product = await getProduct(params.id);
  if (!product) {
    notFound();
  }
  return <div>{product.name}</div>;
}

To display a custom message for this specific route segment, place your fallback UI in app/products/[id]/not-found.tsx. This ensures users see navigation options relevant to the product catalog rather than an ambiguous root-level error screen.

Catching Unexpected Runtime Errors with Boundaries

While not-found states handle predictable missing resources, unexpected runtime exceptions require an error boundary to prevent the entire page from crashing. By adding an error.tsx file to a route segment, you create a React error boundary that catches JavaScript errors thrown by child components during rendering or data fetching.

Error components must be client components because they frequently need to accept an reset function to attempt recovery. A production-ready error boundary should present a clear recovery action alongside an error digest for debugging purposes.

'client'

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

Keep in mind that error.tsx boundaries do not catch errors thrown inside layout files at the same level. To catch layout errors, place an error file in the parent directory so it wraps the offending layout tree.

Distinguishing Between Client and Server Failures

Debugging production failures requires understanding where the exception originated. Server-side data fetching errors and client-side event handler exceptions bubble up differently through the React tree. Use custom error logging utilities inside your error boundaries to capture stack traces before rendering fallback UI to users.

  • Server Fetch Failures: Network timeouts and database connection drops should trigger error boundaries with user-friendly retry buttons.
  • Client Event Errors: Errors inside form submissions or button clicks should be caught with local try-catch blocks rather than triggering page-level error boundaries.
  • Missing Records: Use explicit notFound() calls for expected missing states instead of throwing generic errors.

Checklist for Resilient Error Handling

Before shipping your Next.js application to production, verify your error and not-found configuration against this practical checklist to ensure no edge cases are missed.

  1. Create a root not-found.tsx file to handle unmapped paths across the entire domain.
  2. Add nested not-found.tsx files for major feature sections that require bespoke recovery links.
  3. Implement error.tsx files at strategic layout levels to isolate failures and maintain navigation headers.
  4. Ensure all error boundaries accept and implement the reset callback function.
  5. Test your error boundaries by intentionally throwing mock errors in development environments.

FAQs

Frequently asked questions

Written by

Dipen Nagani, Senior UI/UX Designer

Senior UI/UX Designer

As a User Experience Designer at Seven Square®, I contribute to enhancing digital experiences by leveraging my skills in UI/UX, CSS, and GSAP. My focus is on creating intuitive and visually engaging user interfaces that align with user needs and business goals.

Keep exploring

Put these ideas into practice

Explore a relevant capability, a project example, or a checklist for your next step.

Got an idea?

Let’s turn it into something people love using.

Whether it’s a rough sketch on a napkin or a SaaS product that has grown messy over time, I’d love to hear about it. The first conversation is always free, and if you’re in Ahmedabad, the chai is on me.