🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Error Boundaries, Not Found, and Recovery in Next.js

Next.js PatternsđŸŸĸ Free Lesson

Error Boundaries, Not Found, and Recovery in Next.js

A production application is judged less by its happy path than by what happens when the database times out at 2 a.m. In the App Router, failures are not a single concept: a missing record, a thrown exception inside a component, a failure in the root layout, and a rejected fetch in a child segment are four different situations with four different handlers. Treating them as one generic "catch block" is why so many Next.js apps show a blank white page with a stack trace in the console and nothing at all on screen.

This lesson maps each failure to the file that owns it, shows what reset() actually does, and walks through the difference between telling a user the truth and telling an attacker the truth.

Prerequisites

  • !Server and Client Component boundaries
  • !The folder conventions page.js, layout.js and loading.js
  • !Basic familiarity with try/catch and rejected promises

What You'll Learn

  • 1Place error.js, not-found.js and global-error.js correctly in the tree
  • 2Trigger notFound() from Server Components on missing records
  • 3Use reset() to re-run a failed render instead of reloading
  • 4Report errors to a service without exposing internals to users

Four failure kinds, four owners

The route tree decides which handler runs. An error.js creates a React error boundary around its segment: any throw while rendering that segment or its children — including a rejected await inside a Server Component — bubbles up to the nearest boundary above the failure. not-found.js is separate and is only entered when something calls notFound(). global-error.js is the last line of defence, wrapping the root layout itself, because the root layout sits above every error.js and would otherwise take the whole document down with it.

FileCatchesMust beEntry condition
app/error.jsThrown errors in its segment and belowClient componentAny uncaught throw or rejected await
app/not-found.jsNothing on its ownServer or clientA call to notFound()
app/global-error.jsFailures in the root layoutClient component, renders htmlRoot layout throws
app/[segment]/error.jsOnly that subtreeClient componentFailure inside that segment

Placing error.js too high is the classic mistake. A boundary at app/error.js catches everything, so a failure in a nested page blows away the entire navigation shell. A boundary at app/reports/error.js keeps the sidebar, the header, and every other section alive while only the reports pane degrades.

Route handlers sit outside this system entirely. A route.js file returns a Response; it renders no UI, so no boundary can catch anything it throws — an unhandled rejection there becomes a 500 from the platform and nothing else. Handlers need their own try/catch, their own status codes, and their own logging, which is the subject of the API security lesson rather than this one. The useful mental division is that boundaries protect rendering, while handlers protect the contract.

Writing boundaries that help a real person

An error.js receives the caught error and a reset function. reset() re-renders the segment beneath the boundary — it does not reload the page, does not clear client state outside the boundary, and does not guarantee success on the second attempt. That makes it ideal for transient failures: a flaky upstream call, a rate limit, a cold database connection.

// app/reports/error.js
'use client';

export default function ReportsError({ error, reset }) {
  return (
    <div role="alert">
      <h2>The reports could not be loaded</h2>
      <p>
        Your data is fine — we just could not reach the reporting service.
        Trying again usually clears it.
      </p>
      <button onClick={() => reset()}>Try again</button>
    </div>
  );
}

Three details separate a usable boundary from a decorative one. The role="alert" attribute lets assistive technology announce the failure. The copy names what failed and what state the user's work is in, because "Something went wrong" leaves people unsure whether their save was lost. And the error message shown to the user comes from your own wording rather than from error.message, which may contain a host name or a query fragment.

error.js must be a Client Component — it needs onClick on the button, and React error boundaries are client constructs. It also has to be a default export that takes a props object; there is no way to opt out.

Missing data is not an exception

When a lookup legitimately finds nothing, the correct response is a 404 rather than a caught error. notFound() throws a special error that the router recognises, unwinds to the nearest not-found.js, and returns a 404 status to the browser — which matters for SEO as much as for the user experience.

// app/products/[id]/page.js
import { notFound } from 'next/navigation';
import { getProduct } from '@/lib/products';

export default async function Product({ params }) {
  const { id } = await params;
  const product = await getProduct(id);

  // A product that was deleted is a 404, not a server fault.
  if (!product) notFound();

  // A genuine dependency failure should still throw and hit error.js.
  return <ProductView product={product} />;
}

Keep the two branches separate on purpose. "This id does not exist" is a normal, expected outcome and belongs in the not-found path. "The search cluster refused the connection" is an incident and belongs in error.js, where it can be retried and reported. Collapsing them means your monitoring cannot tell a scraper probing deleted ids from a real outage.

You can also call notFound() during rendering a page that was statically generated, which forces that path to become dynamic — useful when a CMS deletes a document between builds.

The root boundary and what it owns

global-error.js wraps the root layout, so it is the only handler that can run when the layout itself fails. Unlike error.js, it must render its own document: an html element and a body element, because the root layout is where those normally come from and it is exactly what just crashed.

// app/global-error.js
'use client';

export default function GlobalError({ error, reset }) {
  return (
    <html lang="en">
      <body>
        <main style={{ padding: '3rem', textAlign: 'center' }}>
          <h1>The application hit an unexpected error</h1>
          <p>The incident has been logged with a reference id.</p>
          <button onClick={() => reset()}>Reload</button>
        </main>
      </body>
    </html>
  );
}

Because this component replaces the entire document, it cannot rely on your global stylesheet, your font, or your provider tree. Inline styles and system fonts are the correct choice here even though they are usually the wrong choice everywhere else.

Reporting failures without leaking them

Error boundaries are a rendering concern; observability is a separate one, and the two need to be wired together deliberately. The reliable place to capture a Server Component failure is a try/catch around the operation that can fail, because by the time an error reaches a boundary you have lost the request context you would want for logging.

// lib/report-error.js — safe, single-purpose reporting
export async function reportError(error, context) {
  const payload = {
    message: error instanceof Error ? error.message : String(error),
    route: context.route,
    requestId: context.requestId,
    at: new Date().toISOString(),
  };

  // Fire and forget: logging must never block or fail the user's request.
  fetch('https://logs.example.com/ingest', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(payload),
    keepalive: true,
  }).catch(() => {});

  return payload.requestId;
}

Hand the returned id to the user and show the same id in your dashboard. That single correlation turns "our site is broken" into a specific stack trace, without ever printing SQL, host names, tokens, or file paths into HTML that crawlers and attackers can read.

Degradation is a design decision

Not every failure deserves a full-page boundary. A weather widget that cannot reach its provider should render cached data or disappear quietly; a checkout button that cannot reach the payment service must fail loudly and stop the flow. Before you add an error.js, decide what the segment should look like with the failed piece missing. Often the better answer is a narrower Suspense boundary with a skeleton, so only the slow or broken subtree shows anything unusual at all.

Common Mistakes

Putting a single error.js at the root of the app

Fix: Add boundaries next to each section that can fail independently so the shell and sibling routes keep working.

Showing error.message directly to users

Fix: Render your own copy and log the raw message server-side with a request id you can share.

Calling notFound() for every exception

Fix: Reserve notFound() for genuinely missing records; let real faults propagate to error.js so they can be retried and monitored.

Assuming reset() re-fetches your data

Fix: reset() re-renders the segment. If the data comes from a cached or stale source, make that source part of the re-render or the error returns immediately.

Best Practices

  • Give every data-heavy section its own error.js with a working retry action
  • Write error copy for humans first and attach a support or incident id
  • Log with route and request context at the throw site, not at the boundary
  • Test each boundary by forcing a failure: rename an environment variable or stop the dependency

Key Takeaways

  • error.js is a client error boundary for one segment; not-found.js answers notFound(); global-error.js covers the root layout.
  • Boundaries belong as deep as the failure is isolated, so one broken section never unmounts the shell.
  • reset() re-renders the segment in place — ideal for transient faults, useless when the input itself is invalid.
  • Missing records are 404s; dependency failures are exceptions. Keep the paths separate so monitoring stays meaningful.
  • Report errors with a correlation id the user can see, and never print internals into the response body.
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Continue Learning

Suggested next tutorials based on this topic

Need Expert Next.js Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement