Skip to content

When Loading Fails

The Course
•
20 min study

Servers time out, databases go down. A failing page shouldn't take the whole site with it.

A flaky stats service Next.js · 6 files
import Link from "next/link"; import "./globals.css"; export default function RootLayout({ children }) { return ( <html lang="en"> <body> <header> <nav> <Link href="/">Home</Link> <Link href="/stats">Stats</Link> </nav> </header> {children} </body> </html> ); } export default function HomePage() { return ( <main> <h1>Home</h1> <p>Your stats take a moment to work out.</p> </main> ); } body { font: 16px/1.5 system-ui, sans-serif; margin: 0; color: #1c2430; } header, main, footer { max-width: 36rem; margin: 0 auto; padding: 0.75rem 1rem; } header { border-bottom: 1px solid #d6dde6; } nav { display: flex; gap: 1rem; } a { color: #06617f; } h1 { margin: 0.5rem 0; } .muted { color: #5b6876; } .card { border: 1px solid #d6dde6; border-radius: 8px; padding: 0.75rem 1rem; margin-bottom: 0.75rem; } "use client"; import { useEffect } from "react"; // Shown instead of app/stats/page.jsx when it throws. Error files are client // components: they have a button to press. export default function StatsError({ error, retry }) { useEffect(() => { console.log("Stats failed:", error.message); }, [error]); return ( <main> <h1>Stats</h1> <p>Your stats couldn't be loaded.</p> <button onClick={() => retry()}>Try again</button> </main> ); } import { getStats } from "@/lib/stats.js"; // Load fresh data on every request, rather than once when the site is built. export const dynamic = "force-dynamic"; export default async function StatsPage() { const stats = await getStats(); return ( <main> <h1>Stats</h1> <p> {stats.sessions} sessions · {stats.minutes} minutes </p> </main> ); } // A flaky service: the first request fails, later ones work. let requests = 0; export async function getStats() { requests += 1; await new Promise((resolve) => setTimeout(resolve, 300)); if (requests === 1) throw new Error("The stats service timed out."); return { sessions: 12, minutes: 340 }; }
Runs with real Next.js on your computer: unzip, then npm install and npm run dev.
Add and remove files here; write their code in the editor.

Follow Stats. The pretend service fails on its first request. Press Try again.

error.jsx

When app/stats/page.jsx throws, Next.js shows app/stats/error.jsx in its place, inside the layout. The navigation still works, and so does every other page. An error.jsx doesn't catch an error in the layout of its own segment; that needs a boundary higher in the tree. global-error.jsx can handle a root layout failure and must provide its own <html> and <body>.

JavaScript
"use client";

export default function StatsError({ error, retry }) { … }
  • An error file must be a client component: it has a button to press.
  • error is what was thrown. The lab logs error.message to the console.
  • retry() asks the server for this part of the page again, and shows it if it works:
JSX
export default function StatsError({ error, retry }) {
  useEffect(() => {
    console.log("Stats failed:", error.message);
  }, [error]);

  return (
    <main>
      <h1>Stats</h1>
      <p>Your stats couldn't be loaded.</p>
      <button onClick={() => retry()}>Try again</button>
    </main>
  );
}

Don't show error.message to readers

The page shows its own sentence, Your stats couldn't be loaded., not the error's message. On a real site built for production, Next.js hides the messages of errors thrown on the server, because they can contain details that aren't for the public, such as a database's address. The reader gets a generic message instead. Log the real one, to the console here or to an error-tracking service in a real app, and write the reader's message yourself.

retry and reset

Error files also receive reset. It only renders the page again with the same failed result: it doesn't ask the server for anything. That helps when the error came from something in the browser. When data from the server failed, use retry.

Predict

Change the button to call reset() instead of retry(), taking reset from the props. Press Run, follow Stats, and press Try again.

Check your prediction

The error stays: reset() shows the same failed result again, and the server is never asked. Change it back to retry().

Knowing that retry is still working

retry() takes a moment: the server has to render the page again. Until it answers, the button looks exactly as before, so a reader may think nothing happened and press it again.

React's useTransition hook tracks this kind of slow work:

JavaScript
import { useTransition } from "react";

const [isPending, startTransition] = useTransition();
  • startTransition(fn) calls fn and marks the updates it starts as a transition: work that may take a while, during which React keeps showing the current screen instead of a blank one.
  • isPending is true from the moment you call startTransition until everything it started has finished. Then it's false again.

retry() already runs inside a transition, but that one belongs to Next.js, and your component can't see it. Call retry() inside your own startTransition, and the refresh becomes part of your transition, so your isPending covers it.

Trace one press of Try again with this in place:

  1. The click calls startTransition(() => retry()). StatsError renders again with isPending true. The error page is still on screen.
  2. The server renders the stats page again. The pretend service answers this time.
  3. The stats page replaces the error page, and the transition is over. StatsError is gone, so it never renders with false again. Had the service failed a second time, the error page would stay, with isPending back to false.

Predict

Add the hook to StatsError, with a log during render so you can watch it:

JSX
export default function StatsError({ error, retry }) {
  const [isPending, startTransition] = useTransition();
  console.log("isPending:", isPending);

and change the button's click to () => startTransition(() => retry()). Import useTransition next to useEffect. Press Run, follow Stats, then press Try again. What does the console show after the click?

Check your prediction

isPending: true, once, and then the stats appear. Before the click, StatsError logged isPending: false. There is no false afterwards, because the error page is replaced by the stats page when the transition ends. Keep these changes for the exercise, but remove the log.

Exercise

Trying…

While the page is retrying, make the button say Trying… and disable it, so the reader knows something is happening and can't press it twice. Start from the code of the last Predict.

Your working space Next.js · 6 files
import Link from "next/link"; import "./globals.css"; export default function RootLayout({ children }) { return ( <html lang="en"> <body> <header> <nav> <Link href="/">Home</Link> <Link href="/stats">Stats</Link> </nav> </header> {children} </body> </html> ); } export default function HomePage() { return ( <main> <h1>Home</h1> <p>Your stats take a moment to work out.</p> </main> ); } body { font: 16px/1.5 system-ui, sans-serif; margin: 0; color: #1c2430; } header, main, footer { max-width: 36rem; margin: 0 auto; padding: 0.75rem 1rem; } header { border-bottom: 1px solid #d6dde6; } nav { display: flex; gap: 1rem; } a { color: #06617f; } h1 { margin: 0.5rem 0; } .muted { color: #5b6876; } .card { border: 1px solid #d6dde6; border-radius: 8px; padding: 0.75rem 1rem; margin-bottom: 0.75rem; } "use client"; import { useEffect } from "react"; // Shown instead of app/stats/page.jsx when it throws. Error files are client // components: they have a button to press. export default function StatsError({ error, retry }) { useEffect(() => { console.log("Stats failed:", error.message); }, [error]); return ( <main> <h1>Stats</h1> <p>Your stats couldn't be loaded.</p> <button onClick={() => retry()}>Try again</button> </main> ); } import { getStats } from "@/lib/stats.js"; // Load fresh data on every request, rather than once when the site is built. export const dynamic = "force-dynamic"; export default async function StatsPage() { const stats = await getStats(); return ( <main> <h1>Stats</h1> <p> {stats.sessions} sessions · {stats.minutes} minutes </p> </main> ); } // A flaky service: the first request fails, later ones work. let requests = 0; export async function getStats() { requests += 1; await new Promise((resolve) => setTimeout(resolve, 300)); if (requests === 1) throw new Error("The stats service timed out."); return { sessions: 12, minutes: 340 }; }
Runs with real Next.js on your computer: unzip, then npm install and npm run dev.
Add and remove files here; write their code in the editor.
Hint 1: the idea

isPending is an ordinary value during render, like a prop. Anything the button shows can depend on it, including whether it can be pressed.

Hint 2: a first step

Make sure the click goes through startTransition, or isPending never becomes true. Then change the button in two places: an attribute that stops it being pressed, and its text.

Show one solution
JavaScript
import { useEffect, useTransition } from "react";
JavaScript
const [isPending, startTransition] = useTransition();
JSX
<button onClick={() => startTransition(() => retry())} disabled={isPending}>
  {isPending ? "Trying…" : "Try again"}
</button>

disabled stops a second press while the first retry is still running, and the label tells the reader why. Nothing needs resetting afterwards: if the retry works, the stats page replaces the error page; if it fails, isPending is false again and the button comes back. Calling retry() without startTransition would leave isPending false the whole time.

Was this article helpful?

Your response is saved on this device.