Error handling and not-found

Intermediate · 5 min

Expected errors versus uncaught exceptions, error.tsx and global-error.tsx boundaries, notFound() with not-found.tsx, and the status code streaming changes.

Before thisPages and layouts

Codevolution · 5 min

Error handling and not-found

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by CodevolutionReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • Next.js splits errors into expected ones, which you model as return values and show as ordinary UI, and uncaught exceptions, which you throw and let an `error.tsx` boundary catch.
  • An `error.tsx` file is a React error boundary for its segment; it must be a Client Component, receives the `error` and a `retry` function, and bubbles up to the nearest parent boundary.
  • `global-error.tsx` handles errors in the root layout and must render its own `<html>` and `<body>`.
  • `notFound()` plus a `not-found.tsx` file renders a 404 UI; if streaming has already started the status stays 200 and Next.js adds a `noindex` tag.

Two kinds of error, handled differently

Not everything that goes wrong is a bug. A user types a bad email address, a search returns nothing, a payment is declined. Those are expected: part of normal operation, and the UI should say so plainly. Other failures are not expected: a null you did not guard, a database that is down. Those are bugs or outages.

Next.js treats them differently, and mixing them up is the common mistake.

Expected errors are values. Return them, and render them. In a Server Function used with a form, return an object like { error: "Email is invalid" } and read it through React’s useActionState. In a Server Component, check the result of your fetch and render a message or redirect. Do not throw for these.

Uncaught exceptions are thrown, and caught by a boundary.

error.tsx: a boundary per segment

An error.tsx file wraps its segment in a React error boundary. If anything below it throws during render, the boundary swaps in your fallback:

// app/blog/error.tsx
"use client";

export default function Error({
  error,
  retry,
}: {
  error: unknown;
  retry: () => void;
}) {
  return (
    <div>
      <p>Something went wrong.</p>
      <button onClick={() => retry()}>Try again</button>
    </div>
  );
}

Three details. It must be a Client Component, because error boundaries and the retry button need the browser. It receives the error, plus a retry function that re-fetches and re-renders the segment’s children. Errors from a Server Component arrive with a generic message and a digest hash, never the original text, so production does not leak internals; match the digest against your server logs. The Next.js 16.4 docs describe retry as the usual way to recover, and keep reset, which clears the error state and re-renders without refetching. Older tutorials, including the video below, use reset alone. The next package ships its docs under node_modules/next/dist/docs, so check which props your installed version documents.

Boundaries nest. An error bubbles up to the nearest error.tsx above the failing component, so a dashboard widget can fail without taking the page down if you place a boundary close to it. One limit: an error.tsx does not wrap the layout in the same segment, only what is inside it. A failure in that layout is caught by the boundary one level up.

Boundaries catch errors during rendering. Errors in event handlers, timers and other async code run after render, so they are not caught; handle them yourself and store the message in state. For recovery around an arbitrary component rather than a route segment, Next.js 16 also provides catchError.

global-error.tsx

The root layout.tsx has no error.tsx above it, so a crash there needs its own file. app/global-error.tsx replaces the whole document, so it must define <html> and <body> itself, and it does not get your global styles:

"use client";

export default function GlobalError({ retry }: { error: unknown; retry: () => void }) {
  return (
    <html>
      <body>
        <h2>Something went wrong.</h2>
        <button onClick={() => retry()}>Try again</button>
      </body>
    </html>
  );
}

Not found

Call notFound() from next/navigation when a resource does not exist, such as an unknown slug:

import { notFound } from "next/navigation";

export default async function Page({ params }: PageProps<"/blog/[slug]">) {
  const { slug } = await params;
  const post = await getPost(slug);
  if (!post) notFound();
  return <h1>{post.title}</h1>;
}

It throws a special signal, so nothing after it runs, and Next.js renders the nearest not-found.tsx. Put a not-found.tsx in the segment for a tailored message, or in app/ for a site-wide 404. The same file also handles URLs that match no route at all.

The status code gotcha

Before streaming starts, notFound() yields a real 404. After streaming starts, the status line is already sent as 200; the not-found UI still renders and the status stays 200. In both cases Next.js adds <meta name="robots" content="noindex" />. I saw this on a scratch app: with a loading.tsx above a dynamic route, an unknown slug returned 200 with the not-found UI in the body. If you need the real status, resolve existence before the streaming boundary.

What the video covers

Codevolution’s chapters cover an introduction to error handling, simulating an error, implementing error boundaries, customizing error messages, and advanced techniques. It uses Next.js 15, where the props were error and reset, so its retry button calls reset. The not-found and global error videos are linked under deeper.

Where this fits

You can now handle what goes wrong in a route. Next, parallel and intercepting routes covers the layouts that render several routes at once.

Check yourself

  1. 01How should you handle a form validation failure, and how should you handle a bug that throws during render?

    Validation failure is an expected error: return it as a value and render a message, without throwing. A render bug is an uncaught exception: let it throw so the nearest `error.tsx` boundary catches it and shows fallback UI.

  2. 02Why must `error.tsx` be a Client Component?

    React error boundaries are implemented with client-side class component lifecycle methods, so the file needs `"use client"`. It also needs event handlers, such as a retry button.

  3. 03Why does `notFound()` sometimes produce a 200 status instead of 404?

    HTTP status is sent before the body. If streaming has already begun when `notFound()` runs, the status is already committed as 200. Next.js still renders the not-found UI and adds `noindex` so search engines do not index it.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark