Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 72 ยท Routing

loading.tsx, error.tsx and not-found.tsx

Handle slow, broken and missing pages in the Next.js App Router: loading UI, error boundaries with reset, notFound(), global-error and per-segment fallbacks.

Every real page eventually does one of three annoying things: it takes a while, it crashes, or it does not exist. If you do nothing, the visitor stares at a blank screen, sees a stack trace, or lands on a generic 404. The App Router lets you describe all three situations with files, placed in the same folders as your pages, so each part of the URL tree gets its own fallbacks.

In this lesson you learn what loading.tsx, error.tsx, not-found.tsx and global-error.tsx do, where they sit in the component tree, and what they cannot catch. The real framework cannot run on this site, so the Next.js code below is read-only. The runnable examples use React 19 and hand-written error boundaries to reproduce the same behavior, and each one tells you which part is real React and which part is a stand-in for what Next.js does for you.

Three files, three problems

loading.tsx Shown instantly while a segment streams in.
error.tsx Shown when something throws, with a retry button.
not-found.tsx Shown when notFound() is called or no route matches.

Each file only affects its own folder and the folders below it.

1 / 2

loading.tsx: an instant loading state

Put a loading.tsx next to a page.tsx and Next.js wraps that page in a React <Suspense> boundary, using your component as the fallback. When the user navigates to the route, the fallback appears at once while the server finishes rendering the page.

TSX
// app/dashboard/loading.tsx (read-only)
export default function Loading() {
  return <p className="skeleton">Loading your dashboard...</p>;
}
TSX
// app/dashboard/page.tsx (read-only)
export default async function DashboardPage() {
  const orders = await getOrders(); // slow: takes 2 seconds
  return <OrderTable orders={orders} />;
}

Two things make this useful. First, the layout stays on screen: the sidebar and header from app/dashboard/layout.tsx are not inside the boundary, so they remain visible and interactive while only the page area shows the skeleton. Second, navigation is interruptible, so the user can click a different link without waiting for the slow page to finish.

A loading.tsx file covers the whole segment, including every page below it. For finer control, wrap individual slow components in your own <Suspense>. Streaming with Suspense shows how.

error.tsx: a boundary per segment

An error.tsx file wraps the segment's page in a React error boundary. If the page, or anything below it, throws while rendering, the boundary shows your fallback instead of crashing the whole app. Because error boundaries need state, the file must be a Client Component, so it starts with "use client".

TSX
// app/dashboard/error.tsx (read-only)
"use client";

export default function Error({
  error,
  reset,
}: {
  error: Error & { digest?: string };
  reset: () => void;
}) {
  return (
    <div role="alert">
      <h2>The dashboard could not load.</h2>
      <p>Reference: {error.digest}</p>
      <button onClick={() => reset()}>Try again</button>
    </div>
  );
}

The component receives two props. error is the thrown error. For errors thrown in Server Components, production builds do not send the real message to the browser, because it could leak internals; instead error.digest is a short hash you can search for in your server logs. reset re-renders the segment's contents, which is a sensible button for transient failures.

One detail catches people out: the error boundary sits inside the layout of the same segment. That means app/dashboard/error.tsx handles errors from app/dashboard/page.tsx but not from app/dashboard/layout.tsx. A broken layout is caught by the error.tsx one level up. If the root layout itself breaks, there is nothing above it, which is what global-error.tsx is for.

Where each boundary sits

flowchart TD
  L["layout.tsx"] --> T["template.tsx"]
  T --> E["error.tsx<br/>error boundary"]
  E --> S["loading.tsx<br/>Suspense boundary"]
  S --> N["not-found.tsx<br/>not-found boundary"]
  N --> P["page.tsx or child segment"]

Next.js nests these wrappers in a fixed order around each segment's page; the layout stays outside all of them.

Read the diagram from the top. A throw in the page travels upward and is caught by the nearest boundary that handles it: not-found.tsx handles only notFound(), error.tsx handles every other error. Because every segment has its own set of wrappers, a failure in app/shop/cart shows the cart fallback while the rest of the shop stays alive.

Trying it: a segment with loading and error states

The example below is a stand-in. The real Next.js file system conventions are replaced by one Segment component that wraps its page in an error boundary and a Suspense boundary, the same two layers Next.js generates for you. The "header" plays the role of a layout: it keeps its own counter, and the counter survives navigation because the layout is outside the segment. Pick a page, then try the Try again button on the broken one. The data loader fails on its first attempt only, so a retry succeeds.

A segment with loading and error boundaries

Increase the layout counter, then navigate. The number is kept, which mirrors how layouts behave in the App Router. The fallback UI appears inside <main> only, and the header never disappears.

notFound(): the missing-page signal

Some failures are not bugs. A product that does not exist is a normal situation, and the right answer is a 404 page, not an error report. Call notFound() from next/navigation and Next.js stops rendering and shows the closest not-found.tsx.

TSX
// app/products/[id]/page.tsx (read-only)
import { notFound } from "next/navigation";

export default async function ProductPage({
  params,
}: {
  params: Promise<{ id: string }>;
}) {
  const { id } = await params;
  const product = await findProduct(id);

  if (!product) {
    notFound();
  }

  return <h1>{product.name}</h1>;
}
TSX
// app/products/[id]/not-found.tsx (read-only)
import Link from "next/link";

export default function NotFound() {
  return (
    <div>
      <h2>We could not find that product.</h2>
      <Link href="/products">Browse all products</Link>
    </div>
  );
}

notFound() works by throwing a special error (it has a return type of never, so you do not need a return after it). When the response has not started streaming yet, Next.js sends an HTTP 404 status. If streaming has already begun, the status line is already sent as 200, so Next.js adds a noindex meta tag so search engines still skip the page.

A not-found.tsx in app/ plays a second role: it is also shown for every URL that matches no route at all. Segment-level files only react to notFound() calls inside their own segment, so put a friendly one at the root and specialized ones near the data they guard.

The stand-in below shows how the two kinds of failure are told apart. notFound() throws an error with a marker; the not-found boundary renders its fallback only for that marker and rethrows everything else, so a genuine bug reaches the error boundary one level up. Product 7 deliberately has a bug (no guard), product 99 is missing, and /pricing matches no route.

notFound() versus a real bug

Try all four URLs. Product 99 gives the not-found UI, product 7 reaches the error boundary with a plain TypeError, and /pricing falls through to the root not-found. In real Next.js the matching and the boundaries are generated from your folders; the throw-and-catch mechanism underneath is the same.

global-error.tsx: when the root layout breaks

An app/error.tsx cannot catch errors thrown by app/layout.tsx, because it sits inside that layout. For this last-resort case Next.js uses app/global-error.tsx. It replaces the root layout when it renders, so it must define its own <html> and <body> tags, and it must be a Client Component too.

TSX
// app/global-error.tsx (read-only)
"use client";

export default function GlobalError({ reset }: { error: Error; reset: () => void }) {
  return (
    <html lang="en">
      <body>
        <h1>The site is having trouble.</h1>
        <button onClick={() => reset()}>Reload</button>
      </body>
    </html>
  );
}

It is only used in production, since the dev overlay takes over in development, and it should stay small and dependency free because it is the last thing between the visitor and a blank page.

What error boundaries do not catch

React error boundaries only catch errors thrown while rendering. They do not see:

  • Errors in event handlers such as onClick. Use try/catch there and keep the message in state.
  • Errors in asynchronous code that runs after rendering, such as a setTimeout callback.
  • Errors thrown inside Server Actions. Return the error as data instead; Server Actions covers the pattern.

redirect() also works by throwing, and it is handled before error boundaries get a say, so a redirect never triggers error.tsx.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why must error.tsx start with the "use client" directive?

    An error boundary remembers that an error happened, and it can reset itself. That needs client-side state, so the file is a Client Component.
  2. 2. app/dashboard/layout.tsx throws while rendering. Which file shows the fallback?

    A segment's error boundary wraps its page, not its own layout. A broken layout is caught by the error.tsx one level up (or global-error.tsx at the root).
  3. 3. What does calling notFound() inside a page do?

    notFound() throws a marked error and has the return type never. Next.js catches it and renders the nearest not-found.tsx, with a 404 status when the response has not started streaming.
  4. 4. Which problem is NOT caught by error.tsx?

    Error boundaries only handle errors thrown during rendering. Event handler errors must be caught with try/catch.

Summary

  • loading.tsx wraps the segment's page in Suspense so a fallback appears instantly while the layout stays interactive.
  • error.tsx is a Client Component error boundary that receives error and reset; it protects the page below it, not its own layout.
  • notFound() throws a marked signal that renders the nearest not-found.tsx; app/not-found.tsx also handles URLs that match no route.
  • global-error.tsx replaces the root layout when that layout fails, so it defines its own <html> and <body>.
  • Boundaries catch rendering errors only; handle event-handler and Server Action failures yourself.

Next: Templates and Other Special Files