Next.js loading, error, and not-found: Streaming and Suspense Boundaries
Three files, three React primitives. What each catches, why a layout's own error escapes its error.tsx, and the errors a boundary never sees.

Quick Summary
The App Router provides three special files around a page — loading.tsx, error.tsx, and not-found.tsx — and each maps to a different React primitive. loading.tsx is a Suspense fallback for the segment. error.tsx is a client-side error boundary for the segment's subtree. not-found.tsx is the UI rendered when notFound() is called or when a URL does not match.
Streaming follows from Suspense: the server sends the shell immediately and flushes the suspended parts as their data resolves. A loading.tsx gives that for the whole segment; a manual <Suspense> boundary gives it per component and is what you want for one slow widget on an otherwise fast page.
The boundary that catches nothing is the one people file bugs about: an error.tsx does not catch errors thrown in the layout of its own segment (only in its children), so a layout that throws takes the page down to its parent's boundary. global-error.tsx catches the root layout and must render its own <html> and <body>.
Basic Syntax & Core Signatures
// app/dashboard/loading.tsx — Suspense fallback for /dashboard/*
export default function Loading() {
return <div aria-busy="true">Loading dashboard…</div>;
}// app/dashboard/error.tsx — must be a Client Component
"use client";
import { useEffect } from "react";
export default function Error({
error,
reset,
}: {
error: Error & { digest?: string };
reset: () => void;
}) {
useEffect(() => {
reportToSentry(error, { digest: error.digest }); // digest correlates with server logs
}, [error]);
return (
<div role="alert">
<h2>Something went wrong</h2>
<button onClick={() => reset()}>Try again</button>
</div>
);
}// app/not-found.tsx
export default function NotFound() {
return (
<main>
<h1>Not found</h1>
<p>The page you were looking for does not exist.</p>
</main>
);
}// app/global-error.tsx — catches the root layout; replaces the document
"use client";
export default function GlobalError({ error, reset }: { error: Error; reset: () => void }) {
return (
<html>
<body>
<h1>Application error</h1>
<button onClick={() => reset()}>Reload</button>
</body>
</html>
);
}// Manual boundaries: stream one slow part, keep the rest instant
import { Suspense } from "react";
export default function Page() {
const stats = getStats(); // start the promise, do not await
return (
<>
<h1>Overview</h1>
<Suspense fallback={<StatsSkeleton />}>
<Stats promise={stats} />
</Suspense>
</>
);
}Key Comparison Table
| File | Primitive | Must be client | Catches |
|---|---|---|---|
loading.tsx | Suspense fallback | No | Nothing; shows while rendering |
error.tsx | Error boundary | Yes | Children of the segment, not its layout |
global-error.tsx | Error boundary | Yes | Root layout and everything below |
not-found.tsx | UI for notFound() | No | Nothing |
<Suspense> in a page | Suspense boundary | No | Nothing; streams |
| Trigger | Renders |
|---|---|
notFound() in a page | Nearest not-found.tsx with a 404 |
| Unmatched URL | Root not-found.tsx |
| Throw in a Server Component | Nearest parent error.tsx |
| Throw in the root layout | global-error.tsx |
| Rejected promise under Suspense | Nearest error.tsx above the boundary |
| Symptom | Meaning |
|---|---|
| Error page not showing on a layout error | error.tsx does not catch its own layout |
reset() re-renders and fails again | The error is deterministic; the data did not change |
| 404 shows a 200 | notFound() not called; null returned |
| Page waits for the slowest fetch | No Suspense boundary around it |
Practical Edge Cases & Deep Dives
1. reset() retries the render, not the cause
<button onClick={() => reset()}>Try again</button>reset() clears the error boundary and re-renders the segment. If the failure came from a request that will fail again, the user sees a flash and the same error. Two refinements are worth the code: call router.refresh() as well when the data may have changed on the server, and render a fallback that offers a path forward (a link home) rather than only a retry button. Errors thrown in a Server Component do not include their message on the client in production — only digest, which is how you find the matching server log line.
2. Boundaries nest, and the nearest one wins
app/dashboard/error.tsx <- catches pages below /dashboard
app/dashboard/settings/error.tsx <- catches only /dashboard/settingsA throw inside /dashboard/settings is caught by the settings boundary if it exists, otherwise by the dashboard one. The dashboard's own layout throwing is caught by whatever boundary is above the dashboard segment — usually the root, or global-error.tsx if the root layout itself failed. This is why "add an error.tsx in the layout folder" does not protect that layout. The fix is to put the boundary one level up, or to keep the layout's data fetching defensive.
3. not-found.tsx: three different entry points
import { notFound } from "next/navigation";
const post = await getPost(slug);
if (!post) notFound(); // 1. explicit, in a page or handlerThe second entry point is an unmatched URL, which renders the nearest not-found.tsx that applies — the root one for a URL with no matching segment. The third is unstable_rethrow (or simply not catching) around notFound() inside a try; catching it turns a 404 into a 500. In a route handler, notFound() returns a 404 response and renders the boundary's HTML, which some API clients dislike — return Response.json({}, { status: 404 }) there instead.
4. Streaming changes what users see, not what crawlers index
<Suspense fallback={<Skeleton />}>
<Reviews productId={id} />
</Suspense>With a Suspense boundary, the shell and the fast content arrive in the first chunk and the slow part follows. The HTML is still complete for a crawler that reads the whole stream, but the perceived order changes — which is the point. Two costs: each boundary adds a request to the browser's streaming parser, and a boundary that suspends on client-only data produces a visible skeleton on every navigation. Place boundaries around data that is genuinely slow, not around everything.
5. forbidden() and unauthorized(), and the status code you actually want
Next.js added forbidden() and unauthorized() with matching forbidden.tsx/unauthorized.tsx files so an authorization failure can return a 403 or 401 with a proper UI instead of a redirect to login. They are the honest alternative to redirect("/login") in a page, which returns 200 to a crawler and confuses API clients. If the feature flag is not enabled in your version, the pattern is a route handler or middleware returning the status with a rendered message.
6. What the boundary does not catch
An error boundary only catches errors thrown during rendering. An exception inside an onClick handler, a setTimeout, or a promise that nobody awaits does not reach error.tsx — the browser reports an uncaught error and the UI simply does not change. Those paths need their own handling:
async function onClick() {
try {
await save();
} catch (e) {
setError("Save failed"); // local state, not a boundary
}
}The same applies to errors thrown inside a useEffect body (caught only if the effect is inside a boundary that re-renders), and to errors in a Server Action that the client does not await — a rejected action promise surfaces as an unhandled rejection unless the action returns a state object instead of throwing.
Common Runtime & Configuration Mistakes
| Symptom | Cause | Fix |
|---|---|---|
| Nothing catches a layout error | Boundary scope | Move error.tsx one level up |
error.tsx build error: hooks in a server component | Missing "use client" | Add the directive |
| Global error page blank | global-error.tsx renders no <html> | Render the document |
| 404 page returns 200 | Returned null instead of notFound() | Call notFound() |
| Error message hidden in production | Server errors are sanitised | Log by digest on the server |
| Retry loops instantly | reset() with unchanged data | Also router.refresh(), or guide the user |
| Flask of skeleton on every navigation | loading.tsx on a fast route | Remove it, use local Suspense |
| Slow page despite streaming | Data awaited before the boundary | Pass the promise down |
notFound() becomes a 500 | Called inside a try/catch | Rethrow, or call it outside |
| Suspense boundary never shows a fallback | Component is not actually suspending | Ensure an async component under the boundary |
Loading, error, and not-found are three answers to three questions the user will ask: is it coming, did it break, and does it exist. Give each one a boundary at the level where the answer is true, and let streaming deliver the parts that are ready.
Try matching browser tools
All toolsSmall utilities that fit Next.js work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Next.js guides
All Next.js guidesNext.js Static Export, Standalone Output, and Docker Deployment
Export has no server, standalone has a pruned one, and the default expects a full install. The three COPY lines that decide whether a container renders CSS.
Next.js Parallel Routes and Intercepting Routes: Slot Layouts and Modals
Named slots render several pages in one layout, and (.) interception makes a click open over the page while a direct link renders the full route. Why every slot needs default.tsx.
Next.js ISR: Route Revalidate, revalidateTag, and On-Demand Invalidation
Two clocks and one trigger: route revalidate seconds, fetch-level tags, and a webhook that calls revalidateTag. A timer is a ceiling on freshness, never a guarantee.
Next.js Environment Variables: NEXT_PUBLIC_, Build-Time Inlining, and Runtime Config
The prefix decides whether a value is compiled into the browser bundle or stays on the server. One image, two environments, and the choice that follows from it.
More in Next.js
All Next.js guidesThe guides filed next to this one in Next.js, in library order.