Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

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.

~5 min readNext.js
#Next.js#App Router#Streaming#Error Handling
3D illustration of a page frame streaming content chunks with skeleton placeholders and an error shield

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

tsx
// app/dashboard/loading.tsx — Suspense fallback for /dashboard/* export default function Loading() { return <div aria-busy="true">Loading dashboard…</div>; }
tsx
// 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> ); }
tsx
// 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> ); }
tsx
// 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> ); }
tsx
// 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

FilePrimitiveMust be clientCatches
loading.tsxSuspense fallbackNoNothing; shows while rendering
error.tsxError boundaryYesChildren of the segment, not its layout
global-error.tsxError boundaryYesRoot layout and everything below
not-found.tsxUI for notFound()NoNothing
<Suspense> in a pageSuspense boundaryNoNothing; streams
TriggerRenders
notFound() in a pageNearest not-found.tsx with a 404
Unmatched URLRoot not-found.tsx
Throw in a Server ComponentNearest parent error.tsx
Throw in the root layoutglobal-error.tsx
Rejected promise under SuspenseNearest error.tsx above the boundary
SymptomMeaning
Error page not showing on a layout errorerror.tsx does not catch its own layout
reset() re-renders and fails againThe error is deterministic; the data did not change
404 shows a 200notFound() not called; null returned
Page waits for the slowest fetchNo Suspense boundary around it

Practical Edge Cases & Deep Dives

1. reset() retries the render, not the cause

tsx
<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

text
app/dashboard/error.tsx <- catches pages below /dashboard app/dashboard/settings/error.tsx <- catches only /dashboard/settings

A 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

tsx
import { notFound } from "next/navigation"; const post = await getPost(slug); if (!post) notFound(); // 1. explicit, in a page or handler

The 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

tsx
<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:

tsx
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

SymptomCauseFix
Nothing catches a layout errorBoundary scopeMove error.tsx one level up
error.tsx build error: hooks in a server componentMissing "use client"Add the directive
Global error page blankglobal-error.tsx renders no <html>Render the document
404 page returns 200Returned null instead of notFound()Call notFound()
Error message hidden in productionServer errors are sanitisedLog by digest on the server
Retry loops instantlyreset() with unchanged dataAlso router.refresh(), or guide the user
Flask of skeleton on every navigationloading.tsx on a fast routeRemove it, use local Suspense
Slow page despite streamingData awaited before the boundaryPass the promise down
notFound() becomes a 500Called inside a try/catchRethrow, or call it outside
Suspense boundary never shows a fallbackComponent is not actually suspendingEnsure 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 tools

Small utilities that fit Next.js work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Next.js guides

More in Next.js

All Next.js guides

The guides filed next to this one in Next.js, in library order.