Lesson 10 of 27Routing in depth
Error Handling in Next.js
Expected errors as values, unexpected ones in boundaries: error.tsx, global-error, catchError, notFound and redirect, status codes, digests and onRequestError.
At 9:40 on a Monday the analytics API your dashboard calls starts timing out. In a badly built app, the whole dashboard turns into a white "Application error" screen, and support gets a screenshot with nothing useful on it. In a well built one, only the analytics card says "Could not load. Try again", the rest of the page works, and the support ticket includes a short reference code that leads you straight to the stack trace in your logs. The difference is not luck. It is a handful of decisions about which errors you return, which you throw, where boundaries sit, and how errors are reported. This lesson walks through all of them.
Two kinds of errors
Every error handling design starts by splitting failures into two groups.
Expected errors are part of normal operation: a form field is invalid, a slug does not exist, the user is not allowed to see a record, an upstream API returns 404. You know they will happen, and you know what the UI should say. Handle them as values: return them, render them, or call notFound().
Unexpected errors are bugs and outages: a null where you assumed an object, the database is down, a third-party SDK throws. You cannot write a sensible message for each one. Throw them (or just let them throw) and let an error boundary show a fallback.
Mixing the two is the most common mistake. If a Server Action throws for a validation failure, the user loses their form and sees a generic fallback, and in production the message is hidden anyway. Instead, return a result the form can render, as you did with useActionState in Server Actions and Forms:
"use server";
type Result = { ok: true; id: string } | { ok: false; message: string };
export async function createInvoice(_prev: Result | null, formData: FormData): Promise<Result> {
const amount = Number(formData.get("amount"));
if (!Number.isFinite(amount) || amount <= 0) {
return { ok: false, message: "Enter an amount greater than zero." }; // expected
}
const res = await fetch(`${process.env.BILLING_URL}/invoices`, {
method: "POST",
body: JSON.stringify({ amount }),
});
if (res.status === 409) return { ok: false, message: "That invoice number is taken." }; // expected
if (!res.ok) throw new Error(`Billing API ${res.status}`); // unexpected: let it throw
const { id } = await res.json();
return { ok: true, id };
}The rule of thumb: if you can name the error and tell the user what to do about it, return it. If you cannot, throw it, and make sure someone gets paged when it happens often.
error.tsx: a boundary per route segment
An error.tsx file turns its folder into a React error boundary. It must be a Client Component, because error boundaries are a client-side React feature.
"use client";
import { useEffect } from "react";
export default function DashboardError({ error, retry }: { error: unknown; retry: () => void }) {
const digest = error instanceof Error && "digest" in error ? String(error.digest) : undefined;
useEffect(() => {
reportToMonitoring(error); // your client-side reporter
}, [error]);
return (
<div role="alert">
<h2>This section could not load</h2>
{digest && <p>Reference: {digest}</p>}
<button onClick={() => retry()}>Try again</button>
</div>
);
}Details that matter:
errorisunknown. Errors from Server Components arrive asErrorinstances; something thrown in a Client Component arrives as-is and might be a string. Narrow before you read.message.retry()(stable since 16.3) re-fetches and re-renders the boundary's children, so a temporary server failure can recover without a full page reload.reset()still exists but only clears the error state and re-renders on the client. It cannot fix an error that came from a Server Component, because nothing is fetched again. Older code and tutorials usereset; preferretry.- Placement.
error.tsxwrapsloading.tsx,not-found.tsx, the page and nested layouts, but not thelayout.tsxortemplate.tsxof its own folder (you saw this as a tree in App Router Routing). Errors bubble to the nearest boundary above. - You can re-throw. Throwing inside the error component sends the error to the next boundary up, which is useful when a section cannot handle a particular kind of failure.
A sensible default for most apps: one app/error.tsx that catches everything below the root layout, plus a boundary per major feature (app/dashboard/error.tsx, app/settings/error.tsx) so a crash in one area keeps the navigation and sidebar working.
What boundaries do not catch
Error boundaries catch errors during rendering. They do not catch errors in event handlers, in a setTimeout, or in a promise nobody awaits during render. For those, catch the error yourself and put it in state. One useful exception: an error thrown inside startTransition does bubble to the nearest boundary, and so does an error thrown by a Server Action called through a form action (which runs in a transition).
global-error.tsx: when the root layout itself fails
app/error.tsx sits inside the root layout, so it cannot catch an error thrown by app/layout.tsx (for example, a broken auth provider or a font loader issue). For that there is app/global-error.tsx. When it activates it replaces the root layout, so it must render its own <html> and <body>. It also does not get your global CSS, fonts or theme class, and it cannot export metadata; use a React <title> element instead. Keep it plain and self-contained: a heading, a sentence, a reload button. Since 15.2 it also shows in development, so test it there.
catchError (16.3): boundaries anywhere in the tree
Segment boundaries are coarse. A dashboard page might have six independent widgets, and one failing should not blank the other five. Before 16.3 you wrote a class component (as in React's Error Boundaries and Resilient UI lesson) or used react-error-boundary. Those have two problems in Next.js: they can swallow the special errors that redirect() and notFound() throw, and their "try again" cannot re-fetch Server Component data.
catchError from next/error builds a boundary that knows about Next.js:
"use client";
import { catchError, type ErrorInfo } from "next/error";
function WidgetFallback(props: { title: string }, { error, retry }: ErrorInfo) {
console.error(error);
return (
<section role="alert" style={{ minHeight: 160 }}>
<h3>{props.title}</h3>
<p>Could not load this widget.</p>
<button onClick={() => retry()}>Try again</button>
</section>
);
}
export default catchError(WidgetFallback);import { Suspense } from "react";
import WidgetBoundary from "./widget-boundary";
export default function Dashboard() {
return (
<div className="grid">
<WidgetBoundary title="Revenue">
<Suspense fallback={<CardSkeleton />}><Revenue /></Suspense>
</WidgetBoundary>
<WidgetBoundary title="Analytics">
<Suspense fallback={<CardSkeleton />}><Analytics /></Suspense>
</WidgetBoundary>
</div>
);
}The fallback function receives the wrapper's props first (so one boundary can serve every widget) and an ErrorInfo with error, retry and reset. redirect() and notFound() pass straight through it, retry() re-renders server content in a transition, and the error state clears automatically when the user navigates to another route. Note the order: the error boundary goes outside the Suspense boundary, so a failure replaces the skeleton, not the whole page.
The analytics API times out and Analytics throws while rendering on the server.
Here is the same isolation in plain React, so you can feel it. Click "Break analytics", then "Try again".
catchError boundary failed because the database was briefly unreachable. Which recovery actually loads fresh data?redirect, notFound and friends work by throwing
redirect(), permanentRedirect(), notFound(), forbidden() and unauthorized() all stop rendering by throwing a special error that Next.js catches higher up (notFound() throws one whose digest is NEXT_HTTP_ERROR_FALLBACK;404). Their return type is never, so TypeScript narrows after the call and you do not need return notFound().
The trap, as you saw briefly in Layouts and Navigation: a try/catch around the call catches the framework's error too. Run this simulation of the bug and the fix.
Press Run (⌘ Enter) to see what happens.You have three options in real code. Best: call redirect() and notFound() outside the try block, after you have the data. If the call must sit inside, put unstable_rethrow(err) from next/navigation as the first line of the catch (it re-throws framework errors and does nothing for yours). And inside catchError boundaries this is handled for you.
What does this print?
class Signal extends Error {}
const notFound = (): never => { throw new Signal("404"); };
function load(slug: string) {
try {
if (slug !== "hello") notFound();
return "post";
} catch {
return "error page";
} finally {
console.log("cleanup");
}
}
console.log(load("missing"));Not found, unauthorized, forbidden
notFound() renders the nearest not-found.tsx up the tree. The root app/not-found.tsx also handles URLs that match no route. Put the existence check in your data access function, so every page using it gets the 404 for free.
For authentication and authorization failures there are unauthorized() (401) and forbidden() (403), which render app/unauthorized.tsx and app/forbidden.tsx. They are still experimental and need experimental.authInterrupts: true in next.config.ts; check the docs before relying on them. Call them from your data access layer after the session check, so the page cannot forget it. Many teams still simply redirect("/login") for logged-out users and use forbidden() for "logged in, but not yours".
Status codes and streaming
The status code is sent with the first byte of the response. That gives you a rule you need to know for SEO, monitoring and API clients:
- If
notFound(),forbidden()orunauthorized()runs before streaming starts, the response gets a real404,403or401. - If it runs inside a Suspense boundary after the shell has been sent, the status stays
200. Next.js renders the not-found UI in place and adds anoindexmeta tag so search engines skip it. Aredirect()mid-stream becomes a client-side redirect. - An unexpected error inside a streamed boundary renders the nearest error UI in place, and the response is still
200.
Streaming starts when a Suspense fallback first renders (including loading.tsx) or a component suspends. So when a real 404 matters (marketing pages, public profiles, anything an API client or crawler checks), do a fast existence check in the page before any Suspense boundary, then stream the expensive details. Checks in proxy.ts also run before rendering and keep status codes intact; keep them fast.
The monitoring consequence is easy to miss: on streamed pages, your load balancer's 5xx rate does not show render failures. You need application-level error reporting, which is the next section.
<Suspense> boundary whose Article component calls notFound() for an unknown slug. What does a crawler receive?In production: digests, hidden messages and reporting
In development, the error your boundary receives includes the original message. In production, errors from Server Components are redacted: the client gets a generic message plus error.digest, a hash that matches the server log entry. This is deliberate. Error messages often contain SQL, internal hostnames or user data, and they would otherwise travel to the browser in the RSC payload. Errors thrown in Client Components keep their message, because they never left the browser.
Two habits follow. Never render error.message from a server error as user-facing text; write your own copy. And do show the digest as a "reference code", so support tickets lead somewhere.
GET /dashboard
Server errors are reported from onRequestError, exported from instrumentation.ts at the project root (or in src/). Next.js calls it for errors in rendering, Route Handlers, Server Actions and the proxy:
import type { Instrumentation } from "next";
export const onRequestError: Instrumentation.onRequestError = async (err, request, context) => {
const message = err instanceof Error ? err.message : String(err);
const digest =
typeof err === "object" && err !== null && "digest" in err ? String(err.digest) : undefined;
await fetch(process.env.ERROR_TRACKER_URL!, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
message,
digest,
path: request.path,
method: request.method,
route: context.routePath, // e.g. /app/dashboard/page
kind: context.routeType, // "render" | "route" | "action" | "proxy"
renderType: context.renderType, // "dynamic-resume" when filling a prerendered shell
}),
});
};Await any async work inside it. The err you get may be the version React processed during rendering rather than your original instance, which is another reason to key everything on the digest. In practice most teams install their tracker's Next.js SDK (Sentry, Datadog and others hook into this same function) and add instrumentation-client.ts for browser-side setup.
Match each failure to how it should be handled.
- expected error
- A failure that is part of normal operation, like invalid input or a missing record. Return it as a value or call
notFound(). - error boundary
- A component that catches errors thrown while rendering its children and shows a fallback.
error.tsxandcatchErrorcreate them. - retry()
- Error boundary recovery (stable in 16.3) that re-fetches and re-renders the children from the server, unlike
reset(). - global-error.tsx
- The boundary for errors in the root layout. It replaces the whole document, so it renders its own html and body.
- catchError
- A 16.3 function from
next/errorthat builds a Next.js-aware error boundary you can place around any part of the tree. - unstable_rethrow
- Re-throws the internal errors used by
redirect(),notFound()and similar, so a catch block does not swallow them. - digest
- A hash attached to server errors in production. The browser gets the digest instead of the message, and it matches the server log.