You've been writing <Suspense> since 01-04 because Next.js complains without it. This lesson explains the mechanism behind it and, above all, how to use it well. A boundary isn't a formality: it's a decision about what the visitor sees in the first instant, in what order everything else appears and how much the page jumps around while it happens.
You'll open up a response in progress to watch the chunks arrive, use the Navigation Inspector to check what makes up each route's shell, choose where to split, design skeletons that don't move the page, and review what streaming rules out: changing the status code, for example. We'll finish with what can cancel it out without warning, from a proxy to a compressor.
- A response that arrives in parts
In classic rendering, the server builds the entire document and then sends it. The visitor waits as long as the slowest piece of data takes, staring at a blank screen. With streaming, the server sends each part as soon as it's ready, over the same connection and in the same HTTP response.
React decides where the splits are: they're the <Suspense> boundaries. On a full load of /events/river-tales, this is what happens:
sequenceDiagram
participant N as Browser
participant S as Server
N->>S: GET /events/river-tales
S-->>N: Shell: head, header, skeletons, footer
Note over N: First paint and CSS and JavaScript download
S->>S: event and venue, related events
S-->>N: Event page and the script that places it
S-->>N: Related events and the script that places them
S->>S: forecast
S-->>N: Forecast and the script that places it
S--xN: End of the response
The shell (static shell) is everything that doesn't have to wait: layouts, navigation, fixed headings and the boundaries' fallbacks. With Cache Components it's already generated at build time, so it goes out without running anything.
When a boundary resolves, React sends its HTML hidden, along with a small inline script that swaps it in for the fallback. That script isn't part of the application's JavaScript: it runs as soon as it's received, even if the main bundle hasn't arrived and nothing has been hydrated. Along with it travels the RSC Payload for that part, which will be used to hydrate it.
1.1. Seeing it with your own eyes
The usual tools buffer the response. A Node script lets you see the chunks as they arrive:
// scripts/watch-response.mjs — usage: node scripts/watch-response.mjs /events
const path = process.argv[2] ?? '/'
const agent = process.argv[3] ?? 'watcher'
const start = Date.now()
const response = await fetch(new URL(path, 'http://localhost:3000'), {
headers: { 'Accept-Encoding': 'identity', 'User-Agent': agent },
})
console.log(`Status ${response.status} after ${Date.now() - start} ms`)
const reader = response.body.getReader()
const decoder = new TextDecoder()
let count = 0
while (true) {
const { done, value } = await reader.read()
if (done) break
const text = decoder.decode(value, { stream: true })
const holes = text.match(/<template id="B:\d+"/g)?.length ?? 0
const parts = text.match(/<div hidden id="S:\d+"/g)?.length ?? 0
console.log(
`Chunk ${count} (+${Date.now() - start} ms): ${text.length} characters, ` +
`${holes} holes, ${parts} resolved parts`,
)
count += 1
}The timings and sizes will depend on your machine; the pattern won't. The first chunk arrives immediately and contains the holes, some <template id="B:0"> elements. The following ones arrive after each query's delay and bring <div hidden id="S:0">, the content that replaces the hole with the same number. The Accept-Encoding: identity header prevents compression from grouping them together.
You can print text and read it. It's ordinary HTML, with nothing hidden about it except that it arrives in installments.
1.2. During a navigation
When you click a Link, no HTML travels, only the RSC Payload, and it too arrives in parts. The destination's shell is usually prefetched, so the layouts and skeletons appear instantly and the content arrives afterwards. There's one difference that matters when placing boundaries: during a navigation, only what's below the layout shared by the origin and the destination is rendered. A <Suspense> placed higher up, for example in RootLayout, covers the full load and does not cover the navigation. That's why Next.js validates the two cases separately.
- Why Cache Components requires it
Without Cache Components, a single read of request data turns the whole route dynamic, and the page waits. The current model turns that approach around: everything is prerendered except what can't be, and you have to mark the boundary between the two. When prerendering finds an uncached wait, it walks up the tree looking for a <Suspense>:
- It finds one: its fallback goes into the shell and the content is left for the request.
- It doesn't find one: it can't generate a shell. That's the error from 01-04.
This explains why it's required. Without that boundary, the alternative would be to stay silent and leave the page blank while it waits. Next.js prefers that you decide: stream, cache or accept the blocking (instant = false).
It also explains a risk: a boundary that's too high up silences the warning. A loading.tsx at the root makes everything build, and turns the site into a succession of full-page skeletons. No error doesn't mean it's right.
2.1. The Navigation Inspector
To judge a shell you have to see it, and in development it lasts a split second. The Navigation Inspector, which you met by name in 01-02, freezes it:
- Open the Next.js DevTools from the indicator and choose Navigation Inspector.
- Turn on Pause on navigations.
- Reload the page. It stops at the shell, and the panel identifies it as Page load.
- Click Resume to continue.
- Navigate with a link. Now it stops at what's visible right after the click, identified as Client nav, with the origin and the destination.
Go through AgendaViva with it and ask yourself one question on every page: if the visitor only saw this, would they know where they are and what's about to appear? This is the current diagnosis:
| Route | What's in the shell | Assessment |
|---|---|---|
/ |
Headings and "Loading upcoming events…" | The text is replaced by six cards: a big jump |
/events |
Heading and two texts | The form and the list push the footer down |
/events/[slug] |
"Loading the event…" | Nothing suggests an event page |
/venues |
Heading, search box and skeleton | Correct |
/dashboard/events |
Menu and skeleton | Correct: everything depends on the same data |
Turn off the pause when you're done. The Suspense panel in the React DevTools complements this view: it lists the boundaries and lets you toggle each one between its fallback and its content.
- Where to split
A boundary groups everything below it: its content is revealed together. Choosing the granularity means deciding which things should appear at the same time.
| One large boundary | Many small ones | |
|---|---|---|
| First paint | Less real content | More |
| Wait | That of the slowest part | Each one, its own |
| Changes on screen | One | Many: the popcorn effect |
| Risk | Holding back what's fast | Jumps and distraction |
Criteria that work:
- Group what's read together. An event page's title, date and location form a unit. Having the location appear half a second later helps nobody; that's why in 04-03 the join was a visual improvement too.
- Separate the slow from the fast and the secondary from the main. The forecast depends on a third party: it must never hold back the event page.
- Separate what can fail on its own. An
ErrorBoundarywraps its<Suspense>, and both delimit the same area. - What's below the fold can have its own boundary, like the related events.
- Don't put boundaries where there's no wait. An extra one isn't free: on a slow network or with large content, React may show its fallback even if nothing inside suspends.
A tiny loading text for every piece of data is the opposite excess to a page-level loading.tsx. React tempers the effect somewhat: it batches reveals that happen within a short interval, 300 ms according to its documentation, so they don't flicker one after another.
3.1. Sibling and nested boundaries
Siblings are independent: they're revealed in any order. Nested ones impose a visual sequence: the inner one isn't shown, not even its fallback, until the outer one resolves.
<Suspense fallback={<EventDetailsSkeleton />}>
<EventContent params={params} /> {/* inside, another Suspense for the forecast */}
</Suspense>
<Suspense fallback={<CardsSkeleton items={3} columns={3} />}>
<RelatedEvents params={params} />
</Suspense>The forecast is nested, and that's correct: without the event page it has nowhere to go. The related events are siblings. A subtle problem shows up here: they can resolve before the event page and, if its skeleton is small, they'd be seen at the top and then suddenly drop down. With a skeleton the size of the event page, everything takes its place from the start.
3.2. loading.tsx or Suspense
They were compared in 02-04. With what you now know, the rule can be refined:
loading.tsxis a<Suspense>around the page, out of reach of its own layout. Use it when nothing on the page makes sense without the data, like the dashboard listing or the@upcomingand@occupancyslots.- For everything else, explicit boundaries. They let headings, text and forms be in the shell.
3.3. Pushing waits down
The lower down the wait is, the more real content there is in the shell. That's the reason for passing params and searchParams unresolved since 02-02. When it's better for the child to receive the value rather than the promise, there's a compact form: a promise of JSX is valid content for React.
<Suspense fallback={<CardsSkeleton items={3} columns={3} />}>
{params.then(({ slug }) => (
<RelatedEvents slug={slug} />
))}
</Suspense>RelatedEvents would end up with a slug: string prop, which is easier to reuse. Both forms are equivalent; in AgendaViva we'll keep passing the promise, for consistency.
- Skeletons without jumps
When the fallback and the content are different sizes, whatever is below them shifts. That movement is measured with a metric, CLS (10-01), but above all it's suffered: you click where you didn't mean to. A good skeleton takes up the same space as the content and resembles it in shape, not in detail.
The most reliable way to achieve that is to reuse the grid and the same containers:
// components/cards-skeleton.tsx
interface Props {
items?: number
columns?: 2 | 3
}
export function CardsSkeleton({ items = 6, columns = 2 }: Props) {
const grid = columns === 3 ? 'sm:grid-cols-3' : 'sm:grid-cols-2'
return (
<div role="status">
<span className="sr-only">Loading events…</span>
<div aria-hidden className={`grid gap-4 ${grid}`}>
{Array.from({ length: items }, (_, index) => (
<div
key={index}
className="min-h-44 animate-pulse rounded-lg border border-slate-200 p-4 dark:border-slate-700"
>
<div className="h-4 w-20 rounded bg-slate-200 dark:bg-slate-700" />
<div className="mt-3 h-6 w-2/3 rounded bg-slate-200 dark:bg-slate-700" />
<div className="mt-3 h-4 w-1/2 rounded bg-slate-200 dark:bg-slate-700" />
<div className="mt-4 h-10 rounded bg-slate-200 dark:bg-slate-700" />
</div>
))}
</div>
</div>
)
}// app/(public)/events/_components/event-details-skeleton.tsx
const BAR = 'animate-pulse rounded bg-slate-200 dark:bg-slate-700'
export function EventDetailsSkeleton() {
return (
<div role="status" className="min-h-112">
<span className="sr-only">Loading the event…</span>
<div aria-hidden>
<div className={`h-5 w-24 ${BAR}`} />
<div className={`mt-2 h-9 w-2/3 ${BAR}`} />
<div className={`mt-3 h-5 w-64 ${BAR}`} />
<div className={`mt-2 h-5 w-80 max-w-full ${BAR}`} />
<div className={`mt-6 h-20 ${BAR}`} />
<div className={`mt-4 h-5 w-48 ${BAR}`} />
</div>
</div>
)
}The grid classes are written out in full, rather than composed with the number: Tailwind looks for complete strings in the code. Replace the fallbacks according to the diagnosis:
| Place | Fallback |
|---|---|
Home page, UpcomingEvents |
<CardsSkeleton /> |
/events, form |
<div aria-hidden className="mb-6 h-16" />, which reserves its height |
/events, both results boundaries |
<CardsSkeleton /> |
| Event page | <EventDetailsSkeleton /> |
| Event page, forecast | <p className="h-5 text-sm">Checking the forecast…</p> |
| Event page, related events | <CardsSkeleton items={3} columns={3} /> |
| Venue page, the events | <CardsSkeleton items={3} /> |
And give EventCard the same minimum height, min-h-44, so the two match. A few observations:
role="status"with hidden text informs screen readers; the bars are decoration and havearia-hidden.- Don't show fake data. A "0 spots left" while loading will be read as information.
- The fallback must be deterministic. It's part of the shell:
Math.random()to vary widths, or the current time, is a prerendering error. - There's no exact height for everything. A description can take up one line or twenty. Get the top part right; what's at the end causes less shifting.
- If the data is almost always small or absent,
fallback={null}is better than a skeleton that disappears. That's whatSiteNoticedoes.
4.1. What shouldn't wait
The LCP metric (10-01) measures when the main element is painted, which is usually a headline or an image. If it's inside a boundary, it depends on that query. A rule of thumb: the largest thing on the first screen, outside the boundaries whenever possible. On the home page and on /events, the <h1> elements are already in the shell. On the event page, the title is the data; the way to bring it forward is for it to stop being a wait, by caching it and generating the event pages ahead of time (05-02 and 05-05).
- Suspense in the browser
Boundaries aren't only for the server. In 03-03, VenueSearch received a promise and read it with use inside a <Suspense> written in the Client Component. The path is the same: the server starts the query, the shell contains the field and the skeleton, and the value arrives over the same stream.
Boundaries also have another effect in the browser: they split hydration. Without them, React hydrates the page in a single pass that ties up the main thread. With them, it hydrates each area separately and, if the visitor clicks on one, it hydrates that one first. That's selective hydration.
And remember the behavior on updates from 02-04: if the content has already been shown and suspends again inside a transition (and navigations are transitions), React keeps the previous content instead of going back to the fallback. To force it, you change the boundary's key, as EventResults does with the filters.
- The HTTP contract
The status code and the headers travel before the body. As soon as the shell goes out, they can no longer be changed. All the limitations follow from that:
| After it has started… | What happens |
|---|---|
notFound() |
not-found.tsx is shown with noindex; the status code is still 200 |
redirect() |
The redirect happens in the browser, not with a 307 |
| An error in a component | Its error boundary; the rest of the page stays |
| Writing a cookie or a header | Not possible while rendering; it's done in a Server Action or a Route Handler (modules 6 to 8) |
With Cache Components the shell always goes out first, so this applies to any decision made during the request inside the page. If you need a real 404 or redirect, it has to be decided earlier: during prerendering (05-05) or in proxy.ts (07-02).
Errors deserve a clarification. If a component fails after the shell, the server sends the error signal for that boundary and the browser renders the notice from ErrorBoundary or from error.tsx. Check it with a temporary throw in listRelatedEvents: the event page stays intact if its area has its own boundary. Add it:
// app/(public)/events/[slug]/page.tsx
export default function EventDetailPage({ params }: Props) {
return (
<>
<Suspense fallback={<EventDetailsSkeleton />}>
<EventContent params={params} />
</Suspense>
<ErrorBoundary title="We can't load the related events">
<Suspense fallback={<CardsSkeleton items={3} columns={3} />}>
<RelatedEvents params={params} />
</Suspense>
</ErrorBoundary>
</>
)
}6.1. Search engines and other bots
Streamed content is in the response's HTML, so a search engine receives it. Next.js distinguishes two kinds of bot by their user agent:
- Those that run JavaScript like a browser receive the shell and the rest in parts, just like a person.
- Those that only read HTML, like the ones that generate link previews on social networks, skip the prerendered shell: the page is rendered for them and the metadata waits until it's in the
<head>. The list can be adjusted with thehtmlLimitedBotsoption.
The second kind has a practical consequence. For those bots, what was generated at build time for everyone else is run again during the request; if that code depended on something that only exists on the build machine, the page will work for people and fail for them.
With JavaScript disabled, on the other hand, the content arrives but nobody runs the script that places it: the fallbacks stay visible. Whatever is in the shell is visible.
- What cancels out streaming
The server can stream perfectly and the visitor can still receive everything at once at the end, because something along the way buffers the response. There's no error, just a slow page.
| Layer | What happens | Remedy |
|---|---|---|
| Reverse proxy (nginx and similar) | Buffers the response by default | X-Accel-Buffering: no header |
| CDN or load balancer | Some wait for the complete response | Provider configuration |
| Serverless platform | Not all of them stream by default | Enable streaming responses |
| Compression | Accumulates data before emitting | Check how often it flushes |
| Browser | Safari waits until it has received 1024 bytes | None: a real page exceeds that |
For nginx, the documentation suggests sending the header from Next.js:
// next.config.ts
async headers() {
return [
{
source: '/:path*{/}?',
headers: [{ key: 'X-Accel-Buffering', value: 'no' }],
},
]
},We'll come back to it when deploying with Docker (11-05); don't add it for now. With any infrastructure, check rather than assume: run the script from section 1.1 against the public address, or look at the network tab in the browser's tools. An early first byte and a long content download mean it's streaming; everything at the end means something is buffering.
Common Mistakes and Tips
- Putting the
<Suspense>in the same component that waits. The boundary has to be above it. - A single boundary at the root. It builds, and it replaces entire pages; during navigations it doesn't even kick in.
- One boundary for every piece of data. The page assembles itself in jumps.
- Skeletons of a different size, or a spinner where six cards will go.
- The main heading inside a boundary when it was known in advance.
- Expecting a 404 from
notFound()during the request. - The
ErrorBoundaryinside the<Suspense>: the order is error outside, wait inside (02-04). - Testing streaming only in development. Prerenders and shells are judged with
buildandstart, and with your proxy in front.
Exercises
Exercise 1: reading the tree
On this page, A takes 300 ms, B 2 s, C 1 s and D 500 ms. Say what's visible at 0, 400, 1200 and 2500 ms, ignoring React's batching.
<h1>Events</h1>
<Suspense fallback={<p>1</p>}>
<A />
<Suspense fallback={<p>2</p>}>
<B />
</Suspense>
</Suspense>
<Suspense fallback={<p>3</p>}>
<C />
<D />
</Suspense>Solution
| Time | On screen |
|---|---|
| 0 ms | h1, "1", "3" |
| 400 ms | h1, A, "2", "3" |
| 1200 ms | h1, A, "2", C and D |
| 2500 ms | h1, A, B, C and D |
B starts at the same time as A, because they're siblings in the JSX of whoever writes them; the nesting only decides that "2" isn't visible until A finishes. D was ready at 500 ms, but it shares a boundary with C and waits for it.
Exercise 2: redesigning an overview
A "My city" page shows a fixed headline, the day's forecast (external API, 100 ms to 2.5 s), the upcoming events (200 ms), a map of venues (400 ms) and the year's figures (3 s). Propose the boundaries, their fallbacks and what each area would do on failure.
Solution
| Area | Boundary | Fallback | On failure |
|---|---|---|---|
| Headline | None | It's in the shell | |
| Forecast | Its own, small | A fixed-height line | Nothing or a text: it returns a status (04-01) |
| Upcoming events | Its own | CardsSkeleton |
ErrorBoundary |
| Map | Its own | A rectangle the size of the map | ErrorBoundary |
| Figures | Its own, at the bottom | A block the height of the figures | ErrorBoundary |
Events and map could share a boundary if they're read together: 200 and 400 ms are similar, and there'd be one jump fewer. The figures, never with anything else. A single loading.tsx for everything would make the headline wait three seconds.
Exercise 3: diagnosing
A team deploys its application. Locally, the shell appears instantly. In production, the page arrives complete after three seconds, with no skeletons. npm run build && npm run start on the server itself behaves correctly. What do you suspect and how do you confirm it?
Solution
Next.js is streaming, since started directly it works. The difference is what's in front: reverse proxy, load balancer, CDN or compression.
- Run
watch-response.mjson the server againsthttp://localhost:3000, and then against the public address. If only the second delivers a single late chunk, something is buffering. - If you can, repeat it going in through each layer: the proxy without the CDN, for example. The layer that turns several chunks into one is the culprit.
- With nginx, add
X-Accel-Buffering: no. If it persists, check the compression; the script asks foridentity, so compare with a browser too.
Conclusion
Streaming sends the shell first and each boundary when it resolves, in a single response. <Suspense> doesn't speed up the data: it decides what's shown while it arrives and what's revealed together. Place boundaries close to the wait, group what's read at the same time, give each fallback the size of its content and wrap it in an error boundary. In return, the status code is fixed at the start. And since any intermediate layer can undo it, you check it in the real environment.
Until now, what prevented prerendering was almost always a query. There's another family of waits: what's only known when someone knocks on the door. In the next lesson, Request Data: cookies, headers and searchParams, you'll read what each visitor brings with them and use it to offer them the events in their district.
