Explain it simply
Loading, error and not found in plain language
Think of a restaurant. While the food cooks, the waiter says 'one moment' (loading). If the kitchen catches fire, they say 'sorry, please order again' (error). If you order a dish that is not on the menu, they say 'we do not have that' (not found). If all three came out as 'there is a problem', the guest would have no idea what to do next.
The Next.js App Router gives you one file per state, and each works just by being placed in a route folder: loading.tsx, error.tsx and not-found.tsx.
Problem → Why → Solution
The problem: silent clicks and one 'Something went wrong' for everything
The note page below has three problems. For the few seconds while data loads nothing on screen changes, so the user clicks the link again and again. The try/catch hides a missing note, a database outage and a code bug behind the same sentence. Worse, the catch block answers with status 200, so monitoring tools never hear about the failure either.
export default async function NotePage({
params,
}: {
params: Promise<{ id: string }>;
}) {
try {
const { id } = await params;
const note = await getNote(id); // slow: the screen just freezes meanwhile
return <h1>{note!.title}</h1>;
} catch {
// a missing note, an outage and a bug all end up here, as a 200
return <p>Something went wrong.</p>;
}
}Why this matters
Each state should send the user to a different action: wait, try again, or look for another note. The three special files do this at the folder level without any try/catch in page code, and they let errors be logged instead of swallowed.
Core concept: three boundaries at folder level
Place loading.tsx in a folder and Next.js wraps that folder's page (and the nested layouts below it) in <Suspense fallback={<Loading />}> for you. On navigation the layouts above stay on screen immediately and the fallback appears where the page will go; when the data arrives, the page replaces the fallback. The fallback is prefetched, so it appears the moment the link is clicked, and the user can still interrupt the navigation by clicking somewhere else.
error.tsx wraps the folder in a React error boundary. When an exception happens during rendering or inside a Server Component, the error UI appears in place of that segment instead of the whole app collapsing. An error boundary keeps state and reacts to button clicks, so error.tsx must start with "use client". In production, the message of an error coming from a Server Component is replaced by a generic text for safety, and error.digest is provided so you can match it with the server logs.
The name of the retry prop depends on your version. According to the version history in the Next.js docs, unstable_retry was added in 16.2 and became stable as retry in 16.3. retry() re-fetches and re-renders the segment, while the older reset() only clears the error state without fetching again. Check the error.js API reference for the version your project uses.
not-found.tsx is not for bugs but for the expected 'does not exist' state. Calling notFound() in a page renders the nearest not-found.tsx and adds a noindex meta tag. The root app/not-found.tsx also handles URLs that match no route at all. A nested one, such as app/notes/not-found.tsx, answers notFound() calls from every page below it, including app/notes/[id]/page.tsx.
- Data still on its way: loading.tsx
- notFound() called: not-found.tsx
- Exception thrown: error.tsx
- Everything fine: page.tsx
Each file works at folder level, and the one in the nearest parent folder wins.
General pattern
// loading.tsx: no props, shown while the segment streams in
export default function Loading() { return <Placeholder />; }
// error.tsx: must be a Client Component
"use client";
export default function Error({ retry }: { error: unknown; retry: () => void }) {
return <button onClick={() => retry()}>Try again</button>;
}
// not-found.tsx: no props, shown after notFound()
export default function NotFound() { return <Message />; }All three files default-export one component and simply sit in the route folder. Only error.tsx receives props, and only error.tsx needs "use client".
Worked example: three files for the /notes route
The block below shows three files separated by comments; in a real project they are three separate files in the app/notes/ folder. The error component uses the retry prop from Next.js 16.3 onwards.
// app/notes/loading.tsx
export default function Loading() {
return <p>Loading notes…</p>;
}
// app/notes/error.tsx
"use client";
export default function NotesError({
retry,
}: {
error: unknown;
retry: () => void;
}) {
return (
<div role="alert">
<p>We could not load your notes.</p>
<button onClick={() => retry()}>Try again</button>
</div>
);
}
// app/notes/not-found.tsx
export default function NotFound() {
return <h2>This note was not found</h2>;
}Code breakdown
- Instant feedback
return <p>Loading notes…</p>;The UI shown before the data arrives. It appears as soon as navigation starts, so the user knows the click worked.
- Client boundary
"use client";An error boundary needs state and onClick, so this file must be declared a Client Component. Without it, Next.js reports an error.
- The props contract
retry: () => void;Next.js passes error and retry. error is unknown, so narrow it with instanceof Error before reading message. In older versions this slot is reset or unstable_retry.
- Recover
<button onClick={() => retry()}>Try again</button>For a temporary network problem the user can try again themselves, without reloading the whole page.
- The expected miss
return <h2>This note was not found</h2>;The UI shown after notFound(). It is not an error, so it needs no retry button; a link back to the list is more useful.
While data loads, "Loading notes…" appears immediately. An exception shows "We could not load your notes." with a Try again button, and notFound() shows "This note was not found".Which boundary catches what
Inside one segment, Next.js stacks the special files in a fixed order: the layout, inside it the error boundary, inside that loading (Suspense), and inside that not-found and the page. So error.tsx does not wrap the layout.tsx in the same folder: an error in that layout is caught by the parent folder's error.tsx. Errors in the root layout need app/global-error.tsx, which renders its own <html> and <body>.
Nesting inside the app/notes segment
------------------------------------
notes/layout.tsx errors here go to app/error.tsx
+- error boundary (notes/error.tsx)
+- Suspense (fallback: notes/loading.tsx)
+- not-found (notes/not-found.tsx)
+- page (notes/page.tsx)Calling notFound() after streaming has started
Once the response has started streaming (for example, a loading.tsx fallback has been sent), the HTTP status can no longer change and stays 200. Next.js still shows the not-found UI and adds a noindex meta tag, so search engines do not index it. If you need a real 404 status, the check must run before streaming starts (see the Status codes section of the loading.js docs).
In real projects
In real projects
Production apps place these three files according to how important each route is. A dashboard often has one error.tsx for the whole area, while critical routes such as payments get a more specific error.tsx of their own.
- Loading UI is drawn as a skeleton the same size as the content that will arrive, so nothing jumps when the data lands.
- error.tsx sends the error to a reporting service such as Sentry from a useEffect, while the user sees only a polite message and a retry button.
- not-found.tsx offers a search box or popular items so the user never hits a dead end.
- Expected errors such as form validation are returned as values and shown next to the form instead of being thrown (lesson 18).
Common mistakes
Common mistakes
Forgetting "use client" in error.tsx
Error boundaries must be Client Components. Without the directive, Next.js reports an error in dev or build, and the onClick handler would not work anyway. Write "use client" as the first statement of the file, above the imports.
Calling notFound() inside try/catch
notFound() and redirect() work by throwing a special error. Call them inside a try block whose catch swallows everything and the 404 UI never appears; you get the catch fallback instead. Keep only the data fetching inside try and call notFound() outside it.
Throwing for an expected error
An invalid email format or a missing note is not a bug. Throwing makes error.tsx show 'Something went wrong' and can wipe the user's form input. Use notFound() for 'missing', and return validation messages as values.
Best practices
Best practices
- Keep loading.tsx light: no data fetching, just a static skeleton, so it can appear instantly.
- Never show stack traces or raw error.message text in the error UI; tell the user the next step they can take.
- Before deploying, throttle the network in DevTools and try all three states yourself: slow data, a thrown error and an unknown id.
Mini challenge
Mini challenge: make the profile route trustworthy
Write the three files for the app/profile/ folder: a loading skeleton with two cards, an error UI with a retry button and a link back home, and a not-found UI that says the profile does not exist.
- loading.tsx shows two card-sized divs with aria-busy
- error.tsx has "use client" and a button that calls retry()
- error.tsx links back to / with next/link
- not-found.tsx uses wording a user understands
// app/profile/loading.tsx
export default function Loading() {
// TODO: two grey card placeholders inside a container with aria-busy="true"
}
// app/profile/error.tsx
// TODO: mark this file as a Client Component
import Link from "next/link";
export default function ProfileError(/* TODO: type error and retry */) {
// TODO: a short message, a Try again button and a link to "/"
}
// app/profile/not-found.tsx
export default function NotFound() {
// TODO: tell the user this profile does not exist
}Expected: Opening /profile shows two grey cards at once. A failed fetch shows the message, a Try again button and a Back to home link, and notFound() shows 'This profile does not exist.'
Show hint
A skeleton card can be a plain div such as style={{ height: 120, background: "#e5e7eb" }}. Type the error.tsx props as { error: unknown; retry: () => void }.
Show solution
// app/profile/loading.tsx
const card = { height: 120, borderRadius: 12, background: "#e5e7eb" };
export default function Loading() {
return (
<div aria-busy="true" style={{ display: "grid", gap: 16 }}>
<div style={card} />
<div style={card} />
</div>
);
}
// app/profile/error.tsx
"use client";
import Link from "next/link";
export default function ProfileError({
retry,
}: {
error: unknown;
retry: () => void;
}) {
return (
<div role="alert">
<p>Your profile could not be loaded right now.</p>
<button onClick={() => retry()}>Try again</button>
<Link href="/">Back to home</Link>
</div>
);
}
// app/profile/not-found.tsx
export default function NotFound() {
return <p>This profile does not exist.</p>;
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- loading.tsx wraps the page in Suspense automatically and gives instant feedback on navigation.
- error.tsx is a "use client" error boundary that offers retry (reset in older versions).
- notFound() and not-found.tsx keep 'missing' separate from bugs and show a 404 UI with noindex.
- An error boundary does not wrap its own folder's layout; the root layout needs global-error.tsx.
Next.js — Error Handling — Next.js
Next.js — Error Handling — Next.js