Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 4 of 6 · Concept · 20 min · revision 2

Loading, Error and Metadata per Route

Give every route its own waiting state, error boundary and not-found page, and control what crawlers and chat apps read: the three file conventions and the Metadata API, with real streamed responses to show what the browser actually receives.

Contentsand lesson path

What you will learn

  • Add per-route metadata for search and sharing, loading UI and error boundaries so every route fails and waits gracefully.

Prerequisites: React Components & State

01. Why it matters

Three things happen to every route that no feature work asks for, and all three are noticed the moment they are missing: the wait while data loads, the failure when something breaks, and the title a search result or chat preview shows. The App Router turns each into a file convention or an export, so a route carries its own loading.tsx, error.tsx, not-found.tsx and metadata instead of centralising them somewhere that cannot know the route's data.

This lesson uses the running catalog app from the previous two lessons. Everything shown ran on Next.js 16.4.6 and React 19.3.0 with cacheComponents (the create-next-app default), and the curl outputs are from its production build. The interesting part is not the files — they are small — but when each one can act, which depends on whether the response has started streaming.

02. Waiting well: loading.tsx

TypeScript · app/catalog/loading.tsx
export default function Loading() {
  return <p role="status">Loading products…</p>;
}

Dropping this file into app/catalog wraps the segment's page — and its child segments — in a React Suspense boundary. The catalog page takes about 1.2 seconds to produce its list (the running app awaits a short delay to make the effect visible), so the response now arrives in two parts: the shell first, with the fallback in place of the list, then the real content streamed in and swapped in. To see the two parts, a small script prints the time each string first appears in the response body.

JavaScript · capture-stream.js
// Prints when each string first appears in the streamed response.
const url = process.argv[2];
const pending = new Set(["Loading products…", "<h1>Catalog</h1>",
  "<h2>Products</h2>"]);
const t0 = Date.now();

async function main() {
  const res = await fetch(url);
  const reader = res.body.getReader();
  const decoder = new TextDecoder();
  let body = '';
  for (;;) {
    const { done, value } = await reader.read();
    if (done) break;
    body += decoder.decode(value, { stream: true });
    for (const needle of pending) {
      if (!body.includes(needle)) continue;
      console.log(`${Date.now() - t0} ms  ${needle}`);
      pending.delete(needle);
    }
  }
}

main().catch((error) => {
  console.error(error);
  process.exitCode = 1;
});
Terminal
$ node capture-stream.js "http://localhost:3131/catalog"
Illustrative output (timings vary by machine and run)
90 ms  Loading products…
1305 ms  <h1>Catalog</h1>
1306 ms  <h2>Products</h2>

In our run (production build, server and script on the same machine) the fallback arrived about 0.1 seconds into the request and the products about 1.2 seconds later, which is the delay the page awaits; your numbers will differ, but a gap of roughly 1.2 seconds between the first line and the others should remain. The shared layout, the header and the category links all rendered in that first part and stayed interactive, because the boundary wraps the page, not the layout. That is the difference between a route that feels responsive and one that shows nothing until its slowest query finishes — and unlike a spinner bolted on in the client, this fallback is prerendered and ready before the request is made.

03. Failing well: error.tsx and not-found.tsx

TypeScript · app/catalog/error.tsx
'use client';

import { useEffect } from 'react';

export default function CatalogError({
  error,
  retry,
}: {
  error: unknown;
  retry: () => void;
}) {
  useEffect(() => {
    console.error(error);
  }, [error]);

  return (
    <div role="alert">
      <h2>We could not load this part of the catalog</h2>
      <p>Something went wrong on our side. You can try again.</p>
      <button type="button" onClick={() => retry()}>
        Try again
      </button>
    </div>
  );
}

An error.tsx is a React error boundary around the segment. It must start with 'use client' — boundaries are client-side recovery — and in current Next.js versions it receives retry, which re-fetches and re-renders the segment's children (an older reset prop still exists for re-rendering without re-fetching, but retry is the recommended default). The detail page from the routes lesson contains a deliberate fault: /catalog/error-demo throws after reading its params. Requesting it shows a subtlety of streaming.

Terminal
$ curl -si http://localhost:3131/catalog/error-demo | head -1
$ curl -s http://localhost:3131/catalog/error-demo \
  | grep -o 'E{[^}]*}' | head -1
Illustrative output (the digest value changes between requests)
HTTP/1.1 200 OK
E{\"digest\":\"554419301\"}

The status is 200, not 500, because by the time the page threw, the server had already streamed the shell and the loading fallback — the status line went out with them. What reaches the browser instead is an error marker with a digest, and the error boundary recovers in the browser: a visitor sees the error.tsx fallback and can press Try again. Two lessons follow. First, an error boundary cannot fix a status code after streaming has started, so put boundaries where the failure is: a boundary inside the failing segment keeps the surrounding UI alive. Second, console.error(error) is where an error-reporting service hooks in — the browser shows a friendly message; your logs receive the real cause. One boundary more: an error.tsx sits inside its segment's layout, so it cannot catch errors thrown by that layout itself; a parent segment's boundary, or global-error.tsx at the root, handles those.

TypeScript · app/catalog/[slug]/not-found.tsx
import Link from 'next/link';

export default function ProductNotFound() {
  return (
    <div>
      <h2>No such product</h2>
      <p>That item is not in the catalog. It may have sold out or moved.</p>
      <p>
        <Link href="/catalog">Back to the catalog</Link>
      </p>
    </div>
  );
}
Terminal
$ curl -sI http://localhost:3131/catalog/no-such-product | head -1
$ curl -s http://localhost:3131/catalog/no-such-product \
  | grep -oE '<meta name="robots"[^>]*>'
$ curl -sI http://localhost:3131/no-page-here | head -1
$ curl -s http://localhost:3131/no-page-here | grep -oE '<h2>[^<]*</h2>'
Expected output
HTTP/1.1 200 OK
<meta name="robots" content="noindex"/>
HTTP/1.1 404 Not Found
<h2>Page not found</h2>

The two cases behave differently, and the streaming rule explains both. /catalog/no-such-product matches the [slug] route, the shell streams first, and the page's notFound() call lands mid-stream — so the status stays 200 while the not-found UI replaces the fallback and Next.js adds <meta name="robots" content="noindex"/> to keep crawlers out. /no-page-here matches no route at all, so the routing layer answers before anything streams: a real 404 status, with the nearest not-found.tsx — app/not-found.tsx here — rendered inside the layout. The same not-found file serves both jobs; the status code is simply not something a streamed response can still decide.

04. Titles and previews: the Metadata API

TypeScript · app/layout.tsx (excerpt)
export const metadata: Metadata = {
  title: { default: 'Copperleaf Supplies', template: '%s · Copperleaf Supplies' },
  description: 'A small shop catalogue built with the Next.js App Router.',
};

Any Server Component layout or page can export a metadata object; when the values depend on data, it exports an async generateMetadata instead — the detail page does exactly that, reading params and returning the product's title and blurb (shown in the routes lesson). Child metadata merges over parent metadata, and the root layout's title.template wraps every child title, which is how one string produces consistent tabs and search results across the site. The framework turns these exports into the <title>, <meta name="description"> and social-preview tags in the HTML head — for prerendered pages at build time. For pages rendered at request time, Next.js streams the tags: they are appended to the body when generateMetadata resolves, so the UI is not held up, except for bots that cannot run JavaScript (detected by user agent), which get the tags in the head.

Terminal
$ curl -s http://localhost:3131/catalog/gooseneck-kettle \
  | grep -o '<title>[^<]*</title>'
$ curl -s http://localhost:3131/catalog/gooseneck-kettle \
  | grep -oE '<meta name="description"[^>]*>'
Expected output
<title>Gooseneck kettle · Copperleaf Supplies</title>
<meta name="description" content="A precision pour for filter coffee."/>

Both tags are in the initial HTML: the product title wrapped in the site template, and the description taken from the product record. That is the point of server-rendered metadata: many link-preview bots read the HTML and run no JavaScript, so a title set in a client-side effect never reaches them. The same mechanism scales up to per-route Open Graph images and canonical URLs when a project needs them.

05. What usually goes wrong

06. Check your understanding

Practice check · 3 questions

Waiting, failing and metadata

Three situations from the running catalog.

Q1. app/catalog/[slug]/not-found.tsx exists, yet /catalog/no-such-thing renders the product page with nothing found. What is missing?
Q2. A learner presses Try again in the error fallback, but the underlying data failure keeps happening. What does retry() do each time?
Q3. The root layout sets title.template "%s · Copperleaf Supplies". The page app/delivery/page.tsx exports metadata with title "Delivery". What does the browser tab show?
Practice only: not graded, not saved, not evidence.

07. Apply it

Work on the catalog from the previous lessons:

  1. Replace the text fallback with a proper skeleton: a <p role="status"> that screen readers announce, and three grey bars sized like list items. Re-run the stream probe and confirm the skeleton still arrives in the first part of the response.
  2. Make /catalog/error-demo fail only sometimes — for example, when the request includes ?flaky=1 — and observe both paths: the boundary recovering in the browser, and the page rendering normally.
  3. Give the catalog list page its own title (Catalog) and description, and check with curl how the template formats it. Then add openGraph fields and inspect the tags it emits.

The lab assembles these pieces into a full localized app, including a members area guarded by Proxy.

08. Review prompt

Without looking back: what does loading.tsx wrap, and what reached the browser first in the streaming probe? Why did a thrown error produce a 200 status, and what recovered the page? When does notFound() yield a real 404 and when only a noindex tag? And which export produces a per-product title, with what help from the root layout?

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check