Skip to content

Lesson 9 of 27Routing in depth

Streaming, Loading UI and Instant Navigations

How streamed HTML really works, where to put Suspense boundaries, how Link prefetching and Partial Prefetching make clicks instant, and how to prove it in CI.

18 min read0/4 questions

A product manager files a ticket: "Clicking Orders feels broken. Nothing happens for two seconds." A week later a different ticket: "The whole dashboard flashes grey every time I switch tabs." Both bugs live in the same place: where your Suspense boundaries sit, what gets prefetched before the click, and what has to wait for the server. Next.js gives you precise control over all three, and since 16.3 it can even tell you, in development, which navigation will block and why. This lesson is the working knowledge behind fixing both tickets.

What actually goes over the wire

You met the idea of streaming in Rendering Strategies: send what is ready, fill in the rest later. Here is what the bytes look like, because the details explain most of the surprises you will hit.

On a direct visit (typing a URL, a refresh, a link from Google), the server responds with chunked transfer encoding. The first chunk is the static shell: the <head> with CSS and script tags, your layouts, everything static, and the fallback of every <Suspense> boundary. Each fallback is marked with a placeholder such as <template id="B:0">. When a boundary's content is ready, React streams a hidden <div hidden id="S:0"> with the finished HTML plus a tiny inline script that swaps it into place. The swap runs before your JavaScript bundle has even loaded. Alongside the HTML, React streams the RSC payload (pushed into self.__next_f), which it uses later to hydrate.

On a client navigation (clicking a <Link>), no HTML is transferred at all. The router requests only the RSC payload for the segments that change, with an rsc: 1 request header, and React patches the tree in place.

Three consequences follow, and each one shows up in real incidents:

  • The status code is fixed by the first byte. Once the shell is sent, the response is 200. A notFound() that fires inside a streamed boundary cannot become a 404; Next.js injects <meta name="robots" content="noindex"> instead, and a redirect() mid-stream becomes a client-side redirect. The next lesson, Error Handling in Next.js, covers how to keep real status codes.
  • Every layer must pass chunks through. nginx buffers responses by default, so streaming silently becomes one big delayed response. Set the X-Accel-Buffering: no header, and check that your load balancer, CDN and compression layer do not buffer either.
  • Bots get the whole page. For crawlers that only read static HTML, Next.js detects the user agent and waits for the full render before sending anything, so SEO does not depend on your boundaries.

The fastest way to confirm streaming survives your infrastructure is to read the response as a stream and print when each chunk arrives:

scripts/stream-observer.mjs
const res = await fetch("https://staging.example.com/dashboard", {
  headers: { "Accept-Encoding": "identity" }, // no compression buffering
});
const reader = res.body.getReader();
const start = Date.now();
for (let i = 0; ; i++) {
  const { done, value } = await reader.read();
  if (done) break;
  console.log(`chunk ${i} +${Date.now() - start}ms, ${value.length} bytes`);
}

If you see one chunk after three seconds instead of an early chunk and later ones, something between you and Next.js is buffering.

Sibling and nested boundaries

Each <Suspense> boundary is an independent streaming point. Sibling boundaries resolve and reveal on their own schedule. Nested boundaries are different in a way that catches people out: a child async component does not even start rendering until its parent has rendered, so its fetch starts late. Nesting async components is a waterfall unless the data request is started higher up.

Run this simulation of a product page. Reviews and Recommendations are siblings; ReviewPhotos is nested inside Reviews.

TypeScriptstream-order.ts
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));const start = Date.now();const at = () => `${Math.round((Date.now() - start) / 100) * 100}ms`.padStart(6); async function boundary(name: string, ms: number, children: Array<() => Promise<void>> = []) { await sleep(ms); // this component's own data console.log(`${at()} chunk: <${name}> replaces its fallback`); // nested async components only start rendering now await Promise.all(children.map((child) => child()));} console.log(`${at()} chunk: shell with header, price and two fallbacks`);await Promise.all([ boundary("Reviews", 300, [() => boundary("ReviewPhotos", 300)]), boundary("Recommendations", 900),]);console.log(`${at()} response ends`);
Output
Press Run (⌘ Enter) to see what happens.

ReviewPhotos needed only 300ms of work, yet it appeared at 600ms, because its clock started when Reviews finished. If the photos do not depend on the reviews, start both requests in the parent (or in the page) and pass the promise down, or make them siblings.

Predict the outputTypeScript

What does this print?

const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
const order: string[] = ["shell"];
async function b(name: string, ms: number, kids: Array<() => Promise<void>> = []) {
await sleep(ms);
order.push(name);
await Promise.all(kids.map((k) => k()));
}
await Promise.all([
b("Cart", 200, [() => b("Upsell", 100)]),
b("Stock", 250),
]);
console.log(order.join(" "));
Need a nudge? Hints walk you through it.

loading.tsx or Suspense?

loading.tsx is shorthand for a <Suspense> boundary around the page of its folder. Two facts about it matter at work.

First, it does not wrap the layout in the same folder. If app/dashboard/layout.tsx reads cookies() or awaits an uncached query, app/dashboard/loading.tsx cannot show a fallback for it. Without Cache Components the navigation just blocks until the layout finishes. With Cache Components, the build refuses the route and asks you to add a boundary. The fix is to move the data access into the page, or wrap it in its own <Suspense> inside the layout.

Second, a high boundary is a valid boundary. When the prerenderer finds request-time work, it walks up the tree to the nearest Suspense boundary. A loading.tsx near the top satisfies the build, and now every navigation replaces the whole page with one skeleton. That is the "dashboard flashes grey" ticket.

loading.tsx<Suspense>
ScopeThe whole page of its segmentAny component
Prefetched as an instant fallbackYesNot by default; with Partial Prefetching its fallback is part of the App Shell (see below)
Best forPages where nothing useful renders without dataMost pages: put the boundary right around the slow part
Quick check
app/account/layout.tsx awaits getCurrentUser(), which reads cookies(). You add app/account/loading.tsx. With Cache Components on, what happens?
Need a nudge? A hint rules out a wrong answer.

Designing boundaries that feel fast

Passing the build means every page has a shell. It does not mean the loading states are good. A few rules seniors apply:

  • Keep the LCP element in the shell. If the hero image or main heading sits inside a boundary, it cannot paint until that boundary's swap runs. Render it outside, and use the preload prop on next/image for an LCP image.
  • Skeletons must match the final size. When a fallback is replaced by content of a different height, everything below jumps: that is CLS. Give the skeleton the same row heights, or reserve space with a min-height container.
  • Group things that should appear together. Five sibling boundaries resolving at random times make the page "popcorn". If a price and its discount badge are meaningless apart, put them in one boundary.
  • Do not add boundaries you do not need. React may use any boundary under a slow network or a busy CPU, even around fast content. A boundary is a promise that showing its fallback is acceptable.
  • Boundaries help INP too. Each boundary is a separate hydration unit, so React hydrates in smaller tasks and prioritises whatever the user is touching.

Press the button and watch the text under each list. Same data, same delay; only the fallback differs.

Reactskeleton-vs-text.tsx
import { Suspense, use, useState } from "react"; const ROWS = ["Order 1042 shipped", "Order 1041 delivered", "Order 1040 delivered"];const load = () => new Promise<string[]>((r) => setTimeout(() => r(ROWS), 1500));const row = { height: 32, borderBottom: "1px solid #ddd", display: "flex", alignItems: "center" }; function Orders({ data }: { data: Promise<string[]> }) { const rows = use(data); return <div>{rows.map((r) => <div key={r} style={row}>{r}</div>)}</div>;} function Skeleton() { return ( <div> {ROWS.map((r) => ( <div key={r} style={row}><div style={{ width: "60%", height: 12, background: "#e5e5e5" }} /></div> ))} </div> );} export default function App() { const [data, setData] = useState(() => [load(), load()]); const [run, setRun] = useState(0); const column = (title: string, fallback: React.ReactNode, p: Promise<string[]>) => ( <div style={{ flex: 1 }}> <h4>{title}</h4> <Suspense key={run} fallback={fallback}><Orders data={p} /></Suspense> <p style={{ background: "#fff3c4", padding: 4 }}>Content below the list</p> </div> ); return ( <main style={{ fontFamily: "system-ui", fontSize: 14 }}> <button onClick={() => { setData([load(), load()]); setRun(run + 1); }}>Reload both</button> <div style={{ display: "flex", gap: 24 }}> {column("Text fallback", <p>Loading...</p>, data[0])} {column("Sized skeleton", <Skeleton />, data[1])} </div> </main> );}

On the left, the yellow block jumps down when the rows arrive. On the right it never moves.

Page loads and client navigations are different

A direct visit renders the whole tree from the root, so a <Suspense> boundary in the root layout can catch anything. A client navigation from /shop/shoes to /shop/hats only re-renders below the layout the two routes share. A boundary above that point is already showing content and does not trigger. So a route can look instant on refresh and still block on a click, or the reverse.

Client hooks add a twist: useSearchParams() suspends during server rendering (search params are unknown at build time), but on a client navigation the router already has the URL, so it resolves immediately. The same component can sit behind a fallback on a refresh and render at once on a click. Always check both paths.

With Cache Components on, Next.js also keeps a few recently visited routes mounted but hidden using React's <Activity>, instead of unmounting them. Going back restores form inputs and expanded sections. Effects are cleaned up while hidden and re-run when the route shows again, which matters if a dialog or a timer assumed it would unmount.

Prefetching: work done before the click

<Link> prefetches when it scrolls into the viewport, in production only (so do not judge navigation speed in next dev). Without Partial Prefetching, the default prefetches static routes fully and dynamic routes down to their nearest loading.tsx, which is why that file makes clicks feel instant. prefetch={false} turns it off (good for a footer with 200 rarely clicked links), prefetch={true} fetches the full route, and useRouter().prefetch(href) warms a route from code, for example on hover over a card.

Partial Prefetching (16.3)

The old model costs one prefetch per visible link: a table of 50 orders meant 50 requests. Partial Prefetching, turned on with partialPrefetching: true next to cacheComponents: true, changes the unit to one App Shell per route. The App Shell is everything in the route that does not depend on the URL: static UI, cached content, and Suspense fallbacks. All 50 links to /orders/[id] share one prefetched shell, cached in the browser. Content that depends on params or searchParams resolves after the click.

When one link deserves more, <Link prefetch={true}> becomes a per-link prefetch: it also resolves that link's URL data and the cached content behind it, so the order details can be ready before the click. If a route reads cookies() or headers(), its App Shell includes session data and the browser caches it per session. Small segment responses are also bundled into one request ("prefetch inlining", on by default since 16.3).

If you cannot flip the flag for the whole app, opt in one route at a time with export const prefetch = "partial" in its page or layout, or block prefetching of an expensive segment with "force-disabled". The flag is planned to become the default in the next major version.

The three navigation stages of one route
  1. App Shelldefault Link prefetch, one per route
  2. Per-link prefetchLink prefetch={true}: adds params, searchParams
  3. Navigationafter the click: everything else

Every visible <Link> to the route shares one App Shell: static UI, cached content with a stale time of at least 5 minutes, and Suspense fallbacks. On click, this renders instantly.

1/3

Deferring expensive work: prefetch() and navigation() (16.4)

Prefetching has a cost: every prefetch that renders runs your server code. If a widget calls a slow recommendation service, you do not want 30 visible links each triggering it. Next.js 16.4 adds two functions in next/cache that move work to a later stage:

  • await prefetch() keeps the code below it out of the App Shell. It can still run during a per-link prefetch or the navigation.
  • await navigation() keeps the code below it out of both prefetches. It runs only when the user actually navigates.
app/post/[slug]/page.tsx
import { Suspense } from "react";
import { cookies } from "next/headers";
import { cacheLife, navigation } from "next/cache";
 
export default function Page({ params }: PageProps<"/post/[slug]">) {
  return (
    <>
      <Suspense fallback={<p>Loading post...</p>}>
        <PostBody params={params} /> {/* can be in a per-link prefetch */}
      </Suspense>
      <Suspense fallback={<p>Loading comments...</p>}>
        <Comments params={params} /> {/* fallback prefetched, comments are not */}
      </Suspense>
    </>
  );
}
 
async function Comments({ params }: { params: Promise<{ slug: string }> }) {
  await navigation(); // everything below waits for a real navigation
  const { slug } = await params;
  const sort = (await cookies()).get("comment-sort")?.value ?? "newest";
  return <CommentList items={await getComments(slug, sort)} />;
}
 
async function getComments(slug: string, sort: string) {
  "use cache";
  cacheLife("hours");
  return db.comments.list({ slug, sort });
}

How this differs from connection(): connection() says "this needs a real request", which makes the work request-dependent and uncacheable. navigation() and prefetch() only say "not yet". The work below them can still use use cache and keep its lifetime. Both must sit inside a <Suspense> boundary, and both throw if called inside a use cache scope, after(), generateStaticParams or a Client Component. One naming trap: a page that exports the prefetch segment config and also calls the function must import it under another name, such as import { prefetch as prefetchStage } from "next/cache".

Match the pairs0/5 matched

Pick the tool for each situation.

Choose an item, then its match on the other side.

Feedback while waiting: useLinkStatus

When a route is not prefetched yet (prefetch disabled, a slow network, a dynamic route with no shell), the click can feel dead. useLinkStatus() from next/link, called in a Client Component rendered inside a <Link>, returns { pending }. Render a fixed-size hint that is always present and toggle its opacity, so the indicator itself does not shift the layout. If the route was prefetched, pending is skipped. Treat it as a patch: the real fix is a shell or a better prefetch.

Proving it: Instant Insights, the Navigation Inspector and instant()

In a Cache Components app, next dev validates every page by default and reports Instant Insights in the dev overlay. Validation simulates both a page load and client navigations at each shared layout, then names the component that would block, with a message such as Next.js encountered runtime data during prerendering or a navigation and three fixes: stream it (<Suspense>), cache it ("use cache"), or allow the block with export const instant = false. You can also set export const instant = true on a page to state the expectation explicitly. instant = false on a layout lets navigations into that section block while still checking navigations between its children.

The Navigation Inspector in the Next.js DevTools has a "Pause on navigations" toggle. Refresh, and the page freezes at its static shell; click a link, and it freezes at the prefetched UI. It is the quickest way to see what your users see in the first frame. Pair it with the React DevTools Suspense panel to see which boundary covers what.

Validation tells you a shell exists, not that the right content is in it. Lock that in with an end-to-end test using instant() from @next/playwright, which holds back dynamic content while your assertions run:

e2e/product.test.ts
import { test, expect } from "@playwright/test";
import { instant } from "@next/playwright";
 
test("product page is instant on a client navigation", async ({ page }) => {
  await page.goto("/store/shoes");
  await instant(page, async () => {
    await page.click('a[href="/store/hats"]');
    await page.waitForURL((url) => url.pathname === "/store/hats");
    await expect(page.locator("h1")).toContainText("Baseball Cap"); // cached: in the shell
    await expect(page.getByText("In stock")).toHaveCount(0); // live: not yet
  });
  await expect(page.getByText("In stock")).toBeVisible(); // streams in after
});

The testing API is on automatically in next dev. For a production build in CI, set experimental.exposeTestingApiInProductionBuild for the test build only, and set it when you run next build, not just next start.

Quick check
A page passes Instant validation on refresh, but clicking between /shop/shoes and /shop/hats shows nothing for a second. The only Suspense boundary is in the root layout. Why?
Need a nudge? A hint rules out a wrong answer.
Key terms
static shell
The HTML sent first on a direct visit: layouts, static and cached content, and Suspense fallbacks. With Cache Components it is prerendered at build time.
RSC payload
The serialized component tree React uses to hydrate and update. Client navigations fetch only this, never HTML.
App Shell
With Partial Prefetching, the per-route prerender of everything that does not depend on the URL. One is shared by every link to the route.
Partial Prefetching
The 16.3 model (partialPrefetching: true) where a default Link prefetches the route's App Shell instead of the full page.
per-link prefetch
What <Link prefetch={true}> does under Partial Prefetching: also resolves that link's params and searchParams before the click.
navigation stages
App Shell, then per-link prefetch, then the navigation itself. prefetch(), navigation() and ensureStatic move work between them.
Instant Insights
Dev-time validation in Cache Components apps that names the component that would block a page load or navigation, with fixes.