Unverified Commit 3fff1aef authored by Aurora Scharff's avatar Aurora Scharff Committed by GitHub

docs: add Keeping pages static guide and align the navigation stage docs (#99493)

## Summary

- add a **Keeping pages static** guide that applies `ensureStatic =
'shell'`, `'prefetch'`, and `'navigation'` to a store, then works
through the validation errors and fixes in development
- expand **Optimizing prefetching** around the App Shell, per-link
prefetch, and navigation stages, including how `prefetch()` and
`navigation()` defer cached work
- align the `ensureStatic`, `instant`, `prefetch()`, and `navigation()`
references with the guide and clarify how `instant = false` affects
validation
- document blocking generation for complete static output in the Cache
Components ISR guide and update the related migration cross-links
- add reusable docs-diagram tooling and the uploaded light and dark
`ensure-static-visual` and `navigation-stage-visual` assets

This PR is stacked on #97801. #99355 has merged.

The Client fix cards, build-output category, and
`#read-the-data-on-the-client` anchors used by the guide depend on
#99659 and should land first.

## Verification

- Prettier and ESLint passed for the latest documentation changes
through the pre-commit checks
- `bash -n .agents/skills/docs-diagrams/scripts/render.sh`
- guide error ordering and route output were checked against development
and build output

<!-- NEXT_JS_LLM -->

---------
Co-authored-by: 's avatarClaude Fable 5.1 <noreply@anthropic.com>
parent 6bcde44e
---
name: docs-diagrams
description: >
Draw diagrams for the Next.js docs in the style of the ones already
published there: the light/dark PNGs an mdx references with
`<Image srcLight="/docs/light/<name>.png" srcDark="/docs/dark/<name>.png">`.
Use when a guide or API reference needs a new diagram or an existing one
needs a change. Hand-written SVG from a primitives library, rendered by
headless Chrome at 2x. No AI image generation.
disable-model-invocation: true
---
# Docs diagrams
Use the diagrams already published in the docs as references. They share a faint grid background, bordered panels with soft shadows, gray skeleton UI, gray arrows, and a small accent palette in which each color has a consistent meaning. This skill reproduces that visual language from code.
## Files
| Task | Read |
| ------------------------------------------------------------- | ------------------------------------------ |
| Colors, sizes, fonts, what each color means, shape anatomy | [style-tokens.md](style-tokens.md) |
| Reviewing a render before handing it off | [review-checklist.md](review-checklist.md) |
| Primitives: canvas, panels, tree rows, windows, holes, badges | [scripts/lib.mjs](scripts/lib.mjs) |
| Generate SVG + HTML for every diagram module | [scripts/gen.mjs](scripts/gen.mjs) |
| Screenshot light + dark PNGs at 2x | [scripts/render.sh](scripts/render.sh) |
| Measure a render's margins from the ink | [scripts/measure.py](scripts/measure.py) |
## Workflow
### 1. Read the mdx
The `<Image>` block gives you the file names (`srcLight="/docs/light/<name>.png"`), the `width` and `height` the page reserves, and the `alt` text, which is the brief.
The paragraph before the image often states the color legend in words ("gray marks static output and blue marks content that can render at request time"). When it does, the drawing has to match that sentence exactly. When it does not, take the states the alt text names (a Suspense fallback, request-time content), map them with "What the colors mean" in [style-tokens.md](style-tokens.md), and suggest adding the legend sentence to the mdx in your hand-off.
Draw only what the brief names. The alt text and surrounding paragraph determine which values, rows, and labels appear. Use the labels from the alt text and `docs/01-app/04-glossary.mdx` for terminology the brief leaves open.
### 2. Pull references from the docs
The images are not in this repo; they are served from the docs blob store. List what exists and fetch two or three that explain something similar, in both themes, before drawing:
```bash
grep -rhoE 'srcLight="[^"]+"' docs | sort -u
curl -sL -o ref.png "https://h8DxKfmAPhn8O0p3.public.blob.vercel-storage.com/docs/light/nested-layouts.png"
```
Use the full `srcLight` path: most images live under `/docs/`, some under `/learn/`. Swap `light` for `dark` for the dark variant. If the page you are drawing for already has images, those are the first references. Look at more than one: the anatomy is consistent, and you want the shared parts rather than one image's quirks. Published files are a mix of 1x and 2x; that is history, not a target. Always produce 2x.
### 3. Write a diagram module
Copy `scripts/` into a scratch folder outside the repo and add `diagrams/<name>.mjs`:
```js
export default {
name: 'my-diagram', // must equal the mdx srcLight basename
width: 1600, // what the mdx declares
height: 700,
draw(t, lib, { width, height }) {
const k = width / 1600
const s = []
// compose lib primitives here, laid out from a few named constants
return s.join('\n')
},
}
```
`lib.mjs` has the shapes the docs are built from:
- Panels and rows: `panel`, `treePanel`, `urlPill`, `urlStack`, `codePanel`.
- Arrows and captions: `arrow`, `bracketArrow`, `bracketCaption`, `callout`.
- Browser windows: `browserWindow(t, x, y, w, h, url, body = '')` for the frame, `pageLayout` for the page inside it, `postCard` and `commentRows` for the content, `skel.*` for single placeholders. Pass the URL and body as positional arguments.
- States and comparisons: `hole` (not rendered yet), `card` (rendered or highlighted), `grid` (columns and spans for bars).
- Badges and legends: `badge`, `statusBadge`, `legendRow`, `swatchLegend`.
- Text: `label`, `code`, `textWidth` for sizing a block around a label, and the `icons`.
Build a window's page with `pageLayout` rather than placing skeleton atoms by hand. It carries the spacing that makes placeholders read as a page, and returns `regions.post` and `regions.comments` for the usual split of the content column.
When the brief describes moments or stages (before and after, Shell → Prefetch → Navigation), the docs show them as a row of browser windows with arrows between them, each window showing the page at that moment. Content that has rendered at one moment stays rendered, in the same style, in every later moment. When values or APIs need comparing across the moments, bar rows go underneath, split at the gaps between the windows. `grid` lays out those bars; its column headers sit under the windows and double as their captions (the comment on `grid` says how to line the two up). Use `grid` on its own when windows would add nothing.
Lay the block out from named constants and center it on the canvas. When a diagram needs a shape `lib` does not have, add it to `lib.mjs` using the existing tokens, in the same style, so the next diagram gets it too. Never hard-code a color or a one-off offset inside a shape.
A module may export an array of diagrams when several share a drawing. Helper modules without a default export are skipped.
### 4. Render
Run `./render.sh` from inside the scratch folder. It runs `node gen.mjs` and screenshots each `<name>-<theme>.html` with headless Chrome at `--force-device-scale-factor=2`. Output lands in `light/<name>.png` and `dark/<name>.png`, the names the mdx expects. `node gen.mjs <name>` regenerates one diagram while iterating.
The script defaults to the macOS Google Chrome path. On Linux, Windows, or a machine with Chrome installed elsewhere, set `CHROME` to the browser executable:
```bash filename="Terminal"
CHROME=/path/to/chrome ./render.sh
```
### 5. Review
Look at both PNGs at full size, against [review-checklist.md](review-checklist.md) and against the references from step 2. Run `python3 scripts/measure.py light/<name>.png` for the margins. Fix in constants and re-render. Do not hand off a PNG you have not looked at.
### 6. Hand off
Deliver the PNGs with their pixel dimensions and the mdx path each one matches. Uploading to the blob store is a manual step by the docs maintainer, so the PNGs are the deliverable, not a commit. Check that the mdx `srcLight` basename and the PNG name agree, including singular vs plural. If you added a primitive to `lib.mjs`, commit it back into this skill, or hand off the diff if you cannot commit.
## What the docs typically draw
The published diagrams are combinations of a few shapes. These are the common kinds, each with a page where you can see it. There are more, and a new concept may need a new combination.
- **File tree → URL**: a file-tree panel (folder, file, layout and route icons; the row the page is about is bold with a blue dot; elided children are a gray `...` row) with gray arrows to URL pills (globe + path, gray-filled when the path is not routable), bracket arrows beside the tree for which layout wraps which routes, and mono status badges (`Routable`, `Not Routable`). See [Layouts and Pages](https://nextjs.org/docs/app/getting-started/layouts-and-pages) and [Project structure](https://nextjs.org/docs/app/getting-started/project-structure).
- **Files → component hierarchy**: a file list with an arrow to a code panel (React logo and a title in the bar, nested JSX in the docs' syntax colors). See [Project structure](https://nextjs.org/docs/app/getting-started/project-structure).
- **Browser window with skeleton UI**: traffic lights and a URL pill, the page as gray skeleton shapes (avatar, bars, sidebar, image placeholders). Content that has not rendered yet is a dashed hole; content that has arrived or is the subject is a solid accent card, sometimes floated outside the window with a blue arrow. A row of windows with arrows between them shows a sequence; bracket captions underneath name the groups. See [Fetching Data](https://nextjs.org/docs/app/getting-started/fetching-data) and [Caching](https://nextjs.org/docs/app/getting-started/caching).
- **Region map with badges**: a window whose regions are outlined and tinted by category, each tagged with a letter badge, with callouts on leader lines and a legend. The same badges tag rows in a tree and lines in a code panel so the views cross-reference. See [Parallel Routes](https://nextjs.org/docs/app/api-reference/file-conventions/parallel-routes).
- **Zone graph**: dashed, color-coded boxes with a tag in the corner, mono route pills inside, gray arrows between them labelled with mono pills (`SOFT NAV`, `HARD NAV`). See [Multi-zones](https://nextjs.org/docs/app/guides/multi-zones).
Some docs images are product screenshots (DevTools panels, the bundle analyzer, OS dialogs). Capture those from the real UI; this skill does not draw them.
## Conventions
**Canvas.** The docs canvas is 1600 CSS px wide and the page scales it to the column, so the sizes in the tokens are sizes at 1600. For a new diagram, declare 1600 and let the height follow the content. If a page already declares a narrower width, match it and scale element sizes by `k = width / 1600`, otherwise the picture renders larger than its neighbours once the page scales it. `grid`, `swatchLegend`, `arrow`, `pageLayout`, `postCard` and `commentRows` take or derive `k` and scale their defaults by it; pass `× k` sizes to `skel.*`, `hole` and `card` yourself.
**Margins.** The mdx `height` wins: fit the content to the declared box. Top must equal bottom and left must equal right, within 4px; the two pairs need not match each other. Measure from the ink with `scripts/measure.py`, not from the coordinates you passed: text drawn with `dominant-baseline="central"` has its visual top about `0.35 × size` above its `y`, and `textWidth` is a heuristic, so expect to nudge by a few px after measuring.
**Color.** Within one picture a color means exactly one thing in the bars and the legend; if the legend says blue is "request-time content", nothing else may be blue. In the windows, rendered UI is always gray skeleton, whatever the bars say gray means; that is the docs' convention. Blue in a window marks the one state the picture is about (not included in static output, or newly rendered), the same state blue marks in the bars. See "What the colors mean" in [style-tokens.md](style-tokens.md).
**Alignment.** Equal margins, shared edges, text centered in its box, arrows and splits lined up vertically through the whole diagram. This is the review bar.
**Type.** Code and routes in Geist Mono, everything else in Inter. Geist Mono must be installed locally; the fallback is `ui-monospace`.
## Related skills
- `$write-guide` and `$write-api-reference` produce the mdx that references these images.
- `$update-docs` for finding which docs pages a code change touches.
# Review checklist
Open both PNGs at full size next to the reference images, then complete this checklist before handing anything off. Each item comes from a problem found in a real draft.
## Against the references
- [ ] Same kind, same anatomy: a reader could not tell this image was drawn by someone else.
- [ ] Colors mean what they mean in the neighbouring diagrams (see "What the colors mean" in [style-tokens.md](style-tokens.md)). No accent used only to fill the palette.
- [ ] Within this picture every accent means one thing, in every part of the picture (windows, bars, legend).
## Edges and padding
- [ ] Nothing inside a panel touches its border. Holes, cards and rows sit inside the padding.
- [ ] Sibling elements share top and bottom edges (sidebar squares vs content box, tree rows vs their URL pills).
- [ ] Skeleton UI reads as a page: avatars are round and sit in their row, bars have breathing room, the post is a card and the comments are rows, the sidebar is clearly separate from the content. If a window's page was laid out by hand instead of `pageLayout`, check these especially.
- [ ] Every card or hole spans the full width of its content box.
- [ ] Bars and brackets start and end on the edges of the things they describe, to the pixel.
## Composition
- [ ] Left equals right and top equals bottom, within 4px. Measure from the ink with `python3 scripts/measure.py light/<name>.png` rather than trusting the coordinates you passed. The script ignores the grid; panel shadows still count, so the bottom reads a few px smaller than it is.
- [ ] On a canvas narrower than 1600, element sizes were scaled by `width / 1600`, so the picture will not render larger than its neighbours.
- [ ] The whole block is centered as one unit, not each column separately.
- [ ] Arrow heads, bar splits and leader lines line up with what they point at.
- [ ] Captions are centered under their windows or brackets.
## Text
- [ ] Labels are vertically centered (`dominant-baseline="central"`, not a hand-tuned `y`).
- [ ] Inter actually loaded: compare the "a" and "g" with a reference image. If Chrome screenshotted a fallback font, raise `--virtual-time-budget`.
- [ ] Code, routes and mono pills are in Geist Mono.
- [ ] Labels use the docs' terms (App Shell, Suspense fallback, per-link prefetch, Route Group). Check the glossary when unsure.
- [ ] Nothing is clipped at the canvas edge.
## Meaning
- [ ] The colors match the legend sentence in the mdx paragraph before the `<Image>`.
- [ ] Only what the brief names is in the picture: no extra rows, values or labels pulled in from elsewhere.
- [ ] Each frame of a sequence shows the right amount of content for its moment.
- [ ] The alt text in the mdx still describes this picture.
- [ ] Width and height in the mdx match the SVG (the PNG is exactly 2× each).
## Both themes
- [ ] Dark background is `#0D0D0D`, not pure black. Grid lines are visible but faint.
- [ ] Accent fills in dark mode are the navy / plum / wine tokens, not the light-mode pastels.
- [ ] Shadows are stronger in dark mode and barely visible in light mode.
## Files
- [ ] Output names equal the mdx `srcLight` / `srcDark` basenames, including singular vs plural.
- [ ] You handed off `light/<name>.png` and `dark/<name>.png` with their pixel dimensions and the mdx each belongs to.
- [ ] Any primitive you added to `lib.mjs` is committed back into this skill so the next diagram gets it.
// Renders every diagram module in ./diagrams to <name>-<theme>.html and
// <theme>/<name>.svg. render.sh screenshots the HTML files at 2x.
//
// A diagram module default-exports one or more { name, width, height, draw }
// objects; draw(t, lib) returns the SVG body for theme `t`.
import fs from 'node:fs'
import path from 'node:path'
import { fileURLToPath, pathToFileURL } from 'node:url'
import * as lib from './lib.mjs'
const here = path.dirname(fileURLToPath(import.meta.url))
const out = process.cwd()
const only = process.argv[2] // optional: render a single diagram by name
const dir = path.join(here, 'diagrams')
if (!fs.existsSync(dir)) {
console.error(
`No diagrams/ folder next to gen.mjs. Add diagrams/<name>.mjs (see SKILL.md).`
)
process.exit(1)
}
for (const file of fs
.readdirSync(dir)
.filter((f) => f.endsWith('.mjs'))
.sort()) {
const mod = await import(pathToFileURL(path.join(dir, file)).href)
if (!mod.default) continue // a helper module shared between diagrams
const diagrams = [].concat(mod.default)
for (const d of diagrams) {
if (only && d.name !== only) continue
for (const [theme, t] of Object.entries(lib.themes)) {
const width = d.width ?? 1600
const svg = lib.canvas(
t,
width,
d.height,
d.draw(t, lib, { width, height: d.height })
)
fs.mkdirSync(path.join(out, theme), { recursive: true })
fs.writeFileSync(
path.join(out, `${d.name}-${theme}.html`),
lib.html(t, svg)
)
fs.writeFileSync(path.join(out, theme, `${d.name}.svg`), svg)
}
console.log(`generated ${d.name} (${d.width ?? 1600}×${d.height})`)
}
}
// Primitives for Next.js docs diagrams.
//
// Every value here was measured from diagrams already published in the docs
// (see style-tokens.md). Coordinates are CSS px on a canvas that is normally
// 1600 wide; render.sh screenshots at 2x. Keep colors and sizes as tokens on
// the theme object; drawing functions take a theme `t` and return SVG strings.
export const themes = {
light: {
bg: '#FBFBFB',
grid: '#F7F7F7',
// Panels (file trees, URL pills, code panels, browser windows)
panelTop: '#FFFFFF',
panelBottom: '#F9F9F9',
panelStroke: '#D9D9D9',
panelMuted: '#F1F1F1',
divider: '#E8E8E8',
shadow: 'rgba(0,0,0,0.08)',
titleBar: '#F7F7F7',
titleBarDivider: '#E3E3E3',
// Text
text: '#2E2E2E',
textMuted: '#8F8F8F',
textSubtle: '#616161',
icon: '#9A9A9A',
iconMuted: '#CECECE',
arrow: '#A8A8A8',
// Skeleton UI
skel: '#C9C9C9',
// Accents: stroke / light fill / text. Inside a tinted region, skeleton
// bars use `skelOn` and image placeholders `thumbOn`.
blue: {
stroke: '#0070F3',
fill: '#D5E6FA',
text: '#0067D6',
badgeFill: '#CDE7FF',
dot: '#197DF3',
skelOn: '#A8B9CD',
thumbOn: '#C1D2E5',
},
purple: {
stroke: '#8E4EC6',
fill: '#EAE0F2',
text: '#793AAF',
badgeFill: '#EDDBF9',
skelOn: '#BFB6C8',
thumbOn: '#D6CDDF',
},
red: {
stroke: '#E5484D',
fill: '#F7DFE0',
text: '#CA2A30',
badgeFill: '#F5DDDE',
},
green: {
stroke: '#46A758',
fill: '#DCEBDF',
text: '#46A758',
badgeFill: '#DCEBDF',
},
gray: {
stroke: '#8F8F8F',
fill: '#DEDEDE',
text: '#666666',
badgeFill: '#DEDEDE',
},
// A static / prerendered region in a bar or grid cell: lighter than `gray`
static: {
stroke: '#C9C9C9',
fill: '#F1F1F1',
text: '#666666',
badgeFill: '#F1F1F1',
},
// Code (GitHub Light, as used in the component hierarchy panels)
code: {
tag: '#005CC5',
attr: '#6F42C1',
keyword: '#D73A49',
ident: '#E36209',
punct: '#909295',
plain: '#2E2E2E',
react: '#61DAFB',
},
trafficLights: ['#FF6059', '#FFBD2E', '#28CA42'],
},
dark: {
bg: '#0D0D0D',
grid: '#161616',
panelTop: '#313131',
panelBottom: '#282828',
panelStroke: '#484848',
panelMuted: '#1F1F1F',
divider: '#434343',
shadow: 'rgba(0,0,0,0.5)',
titleBar: '#232323',
titleBarDivider: '#3A3A3A',
text: '#D4D4D4',
textMuted: '#A1A1A1',
textSubtle: '#8F8F8F',
icon: '#888888',
iconMuted: '#555555',
arrow: '#878787',
skel: '#4A4A4A',
blue: {
stroke: '#0A72EF',
fill: '#10233D',
text: '#52A8FF',
badgeFill: '#0D2A4D',
dot: '#0761C9',
skelOn: '#2F4A6E',
thumbOn: '#1E3657',
},
purple: {
stroke: '#9A5CD0',
fill: '#2A1F38',
text: '#C4A1E6',
badgeFill: '#2F2240',
skelOn: '#4A3D5C',
thumbOn: '#3A2E49',
},
red: {
stroke: '#E5484D',
fill: '#3A1D1F',
text: '#F08A8E',
badgeFill: '#3A1D1F',
},
green: {
stroke: '#46A758',
fill: '#1B2E1F',
text: '#6FCB80',
badgeFill: '#1B2E1F',
},
gray: {
stroke: '#6F6F6F',
fill: '#2A2A2A',
text: '#B0B0B0',
badgeFill: '#2A2A2A',
},
static: {
stroke: '#4A4A4A',
fill: '#1F1F1F',
text: '#B0B0B0',
badgeFill: '#1F1F1F',
},
code: {
tag: '#79B8FF',
attr: '#B392F0',
keyword: '#F97583',
ident: '#FFAB70',
punct: '#8B949E',
plain: '#D4D4D4',
react: '#61DAFB',
},
trafficLights: ['#FF6059', '#FFBD2E', '#28CA42'],
},
}
export const sans = `font-family="Inter, system-ui, sans-serif"`
export const mono = `font-family="'Geist Mono', ui-monospace, monospace"`
// Snap a 1px stroke to the half pixel so it renders crisp at 1x and 2x.
const half = (v) => Math.round(v) + 0.5
let idCounter = 0
const uid = (prefix) => `${prefix}${++idCounter}`
// ---------------------------------------------------------------------------
// Canvas
export function canvas(t, W, H, body) {
return [
`<svg xmlns="http://www.w3.org/2000/svg" width="${W}" height="${H}" viewBox="0 0 ${W} ${H}">`,
`<defs>`,
`<pattern id="grid" width="40" height="40" patternUnits="userSpaceOnUse"><path d="M40 0H0V40" fill="none" stroke="${t.grid}" stroke-width="1"/></pattern>`,
`<filter id="shadow" x="-20%" y="-20%" width="140%" height="160%"><feGaussianBlur stdDeviation="8"/></filter>`,
`<linearGradient id="panel" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="${t.panelTop}"/><stop offset="1" stop-color="${t.panelBottom}"/></linearGradient>`,
`</defs>`,
`<rect width="${W}" height="${H}" fill="${t.bg}"/><rect width="${W}" height="${H}" fill="url(#grid)"/>`,
body,
`</svg>`,
].join('\n')
}
// Wrap diagram HTML so headless Chrome waits for Inter before screenshotting.
export function html(t, svg) {
return `<!doctype html><html><head><link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600&display=block" rel="stylesheet"><style>html,body{margin:0;background:${t.bg}}svg{display:block}</style></head><body>${svg}</body></html>`
}
// ---------------------------------------------------------------------------
// Text
export function label(
t,
x,
y,
str,
{
size = 20,
weight = 400,
color = t.text,
anchor = 'start',
font = sans,
} = {}
) {
return `<text x="${x}" y="${y}" text-anchor="${anchor}" dominant-baseline="central" font-size="${size}" font-weight="${weight}" fill="${color}" ${font}>${esc(str)}</text>`
}
export function code(t, x, y, str, opts = {}) {
return label(t, x, y, str, { font: mono, ...opts })
}
// Approximate rendered width of a string. There are no font metrics at
// generation time, so this is the heuristic the primitives use; use it in
// modules too when a block's width depends on a label.
export function textWidth(str, size, { mono: isMono = false } = {}) {
return String(str).length * size * (isMono ? 0.58 : 0.52)
}
export const esc = (s) =>
String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
// ---------------------------------------------------------------------------
// Panels
// A white-to-off-white card with a 1px border and a soft shadow. Base for the
// file tree, URL pill, code panel and browser window.
export function panel(
t,
x,
y,
w,
h,
{
radius = 10,
shadow = true,
fill = 'url(#panel)',
stroke = t.panelStroke,
} = {}
) {
const s = []
if (shadow)
s.push(
`<rect x="${x}" y="${y + 6}" width="${w}" height="${h}" rx="${radius}" fill="${t.shadow}" filter="url(#shadow)"/>`
)
s.push(
`<rect x="${half(x)}" y="${half(y)}" width="${w - 1}" height="${h - 1}" rx="${radius}" fill="${fill}" stroke="${stroke}"/>`
)
return s.join('\n')
}
// ---------------------------------------------------------------------------
// Icons (18px glyphs, drawn at x,y = top-left, stroke 1.5)
export const icons = {
folder: (x, y, c) =>
`<path d="M${x + 1.5} ${y + 5} a1.5 1.5 0 0 1 1.5 -1.5 h4.2 l2 2 h6.3 a1.5 1.5 0 0 1 1.5 1.5 v7.5 a1.5 1.5 0 0 1 -1.5 1.5 h-12.5 a1.5 1.5 0 0 1 -1.5 -1.5 z" fill="none" stroke="${c}" stroke-width="1.5" stroke-linejoin="round"/>`,
file: (x, y, c) =>
`<path d="M${x + 4} ${y + 1.5} h6 l4 4 v9.5 a1.5 1.5 0 0 1 -1.5 1.5 h-8.5 a1.5 1.5 0 0 1 -1.5 -1.5 v-12 a1.5 1.5 0 0 1 1.5 -1.5 z M${x + 10} ${y + 1.5} v4 h4" fill="none" stroke="${c}" stroke-width="1.5" stroke-linejoin="round"/>`,
layout: (x, y, c) =>
`<rect x="${x + 2}" y="${y + 2.5}" width="14" height="13" rx="1.5" fill="none" stroke="${c}" stroke-width="1.5"/><path d="M${x + 2} ${y + 7} H${x + 16} M${x + 7} ${y + 7} V${y + 15.5}" stroke="${c}" stroke-width="1.5"/>`,
globe: (x, y, c) =>
`<circle cx="${x + 9}" cy="${y + 9}" r="7" fill="none" stroke="${c}" stroke-width="1.5"/><path d="M${x + 2} ${y + 9} H${x + 16} M${x + 9} ${y + 2} c-3 2.5 -3 11.5 0 14 M${x + 9} ${y + 2} c3 2.5 3 11.5 0 14" fill="none" stroke="${c}" stroke-width="1.5"/>`,
lock: (x, y, c) =>
`<rect x="${x + 4}" y="${y + 8}" width="10" height="8" rx="1.5" fill="${c}"/><path d="M${x + 6} ${y + 8} V${y + 6} a3 3 0 0 1 6 0 V${y + 8}" fill="none" stroke="${c}" stroke-width="1.5"/>`,
route: (x, y, c) =>
`<path d="M${x + 11} ${y + 3} c-3 0 -3 3 -3 5 v6 M${x + 5} ${y + 9} h6" fill="none" stroke="${c}" stroke-width="1.5" stroke-linecap="round"/>`,
react: (x, y, c) => {
const cx = x + 9,
cy = y + 9
return (
[0, 60, 120]
.map(
(a) =>
`<ellipse cx="${cx}" cy="${cy}" rx="8" ry="3" fill="none" stroke="${c}" stroke-width="1.2" transform="rotate(${a} ${cx} ${cy})"/>`
)
.join('') + `<circle cx="${cx}" cy="${cy}" r="1.6" fill="${c}"/>`
)
},
}
// ---------------------------------------------------------------------------
// File tree panel: the "app / page.js → URL" family.
//
// rows: [{ label, icon, depth = 0, bold, dot, muted }]
// Returns { svg, rowY(i) } so arrows can be aligned to rows.
export const TREE_ROW = 80
export function treePanel(t, x, y, w, rows, { indent = 40, pad = 32 } = {}) {
const h = rows.length * TREE_ROW
const s = [panel(t, x, y, w, h)]
rows.forEach((r, i) => {
const ry = y + i * TREE_ROW
if (r.muted) {
const rx = half(x),
ryy = half(ry)
const isLast = i === rows.length - 1
s.push(
`<path d="M${rx} ${ryy} H${rx + w - 1} V${ryy + TREE_ROW - 1 - (isLast ? 10 : 0)} ${isLast ? `a10 10 0 0 1 -10 10 H${rx + 10} a10 10 0 0 1 -10 -10` : `H${rx}`} Z" fill="${t.panelMuted}"/>`
)
}
if (i > 0)
s.push(
`<line x1="${x + 1}" x2="${x + w - 1}" y1="${half(ry)}" y2="${half(ry)}" stroke="${t.divider}"/>`
)
const ix = x + pad + (r.depth || 0) * indent
const color = r.muted ? t.iconMuted : t.icon
if (r.icon) s.push(icons[r.icon](ix, ry + TREE_ROW / 2 - 9, color))
s.push(
label(t, ix + 32, ry + TREE_ROW / 2, r.label, {
weight: r.bold ? 600 : 400,
color: r.muted ? t.textMuted : t.text,
})
)
if (r.dot) s.push(dot(t, x + w - pad - 10, ry + TREE_ROW / 2))
})
return { svg: s.join('\n'), h, rowY: (i) => y + i * TREE_ROW + TREE_ROW / 2 }
}
// The blue "this is the file we are talking about" marker, with a soft glow.
export function dot(t, cx, cy, color = t.blue) {
return `<circle cx="${cx}" cy="${cy}" r="16" fill="${color.fill}" opacity="0.8"/><circle cx="${cx}" cy="${cy}" r="10" fill="${color.dot}"/>`
}
// URL pill: globe + path. `muted` renders the "not routable" variant.
export function urlPill(
t,
x,
y,
w,
path,
{ muted = false, h = TREE_ROW } = {}
) {
const s = [
panel(t, x, y, w, h, { fill: muted ? t.panelMuted : 'url(#panel)' }),
]
s.push(icons.globe(x + 32, y + h / 2 - 9, muted ? t.iconMuted : t.icon))
s.push(
label(t, x + 64, y + h / 2, path, { color: muted ? t.textMuted : t.text })
)
return s.join('\n')
}
// Stack several URL pills into one panel (dividers between them).
export function urlStack(t, x, y, w, paths) {
const h = paths.length * TREE_ROW
const s = [panel(t, x, y, w, h)]
paths.forEach((p, i) => {
const ry = y + i * TREE_ROW
if (p.muted)
s.push(
`<rect x="${x + 1}" y="${ry + 1}" width="${w - 2}" height="${TREE_ROW - 2}" rx="${i === 0 || i === paths.length - 1 ? 10 : 0}" fill="${t.panelMuted}"/>`
)
if (i > 0)
s.push(
`<line x1="${x + 1}" x2="${x + w - 1}" y1="${half(ry)}" y2="${half(ry)}" stroke="${t.divider}"/>`
)
s.push(
icons.globe(x + 32, ry + TREE_ROW / 2 - 9, p.muted ? t.iconMuted : t.icon)
)
s.push(
label(t, x + 64, ry + TREE_ROW / 2, p.path, {
color: p.muted ? t.textMuted : t.text,
})
)
})
return s.join('\n')
}
// ---------------------------------------------------------------------------
// Arrows
// Straight horizontal arrow with an open chevron head.
export function arrow(
t,
x1,
x2,
y,
{ color = t.arrow, width = 2, k = 1 } = {}
) {
const dir = x2 > x1 ? 1 : -1
const hx = x2 - dir * 10 * k
return (
`<line x1="${x1}" x2="${x2 - dir}" y1="${y}" y2="${y}" stroke="${color}" stroke-width="${width * k}" stroke-linecap="round"/>` +
`<path d="M${hx} ${y - 7 * k} L${x2} ${y} L${hx} ${y + 7 * k}" fill="none" stroke="${color}" stroke-width="${width * k}" stroke-linecap="round" stroke-linejoin="round"/>`
)
}
// Bracket arrow used beside file trees: leaves row `fromY` to the left, drops
// to row `toY`, and points back in. `x` is the panel's left edge.
export function bracketArrow(
t,
x,
fromY,
toY,
{ reach = 60, color = t.arrow } = {}
) {
const bx = x - reach
return (
`<path d="M${x} ${fromY} H${bx + 10} a10 10 0 0 0 -10 10 V${toY - 10} a10 10 0 0 0 10 10 H${x - 2}" fill="none" stroke="${color}" stroke-width="2" stroke-linecap="round"/>` +
`<path d="M${x - 10} ${toY - 7} L${x} ${toY} L${x - 10} ${toY + 7}" fill="none" stroke="${color}" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>`
)
}
// Caption bracket under a group of things, with centered text beneath it.
export function bracketCaption(t, x1, x2, y, text) {
return (
`<path d="M${x1} ${y - 12} v4 a8 8 0 0 0 8 8 H${x2 - 8} a8 8 0 0 0 8 -8 v-4" fill="none" stroke="${t.arrow}" stroke-width="2" stroke-linecap="round"/>` +
label(t, (x1 + x2) / 2, y + 40, text, {
size: 20,
color: t.textMuted,
anchor: 'middle',
})
)
}
// ---------------------------------------------------------------------------
// Browser window. Proportions are the docs' 527×476 window at 1600 wide; pass
// a smaller `w` and everything scales with it.
export function browserWindow(t, x, y, w, h, url, body = '') {
const k = w / 527 // scale factor relative to the reference window
const bar = Math.round(70 * k)
const r = Math.round(12 * k)
const s = [panel(t, x, y, w, h, { radius: r })]
s.push(
`<path d="M${half(x)} ${half(y) + bar} V${half(y) + r} a${r} ${r} 0 0 1 ${r} -${r} H${half(x) + w - 1 - r} a${r} ${r} 0 0 1 ${r} ${r} V${half(y) + bar} Z" fill="${t.titleBar}"/>`
)
s.push(
`<line x1="${x + 1}" x2="${x + w - 1}" y1="${half(y + bar)}" y2="${half(y + bar)}" stroke="${t.titleBarDivider}"/>`
)
t.trafficLights.forEach((c, i) =>
s.push(
`<circle cx="${x + 37 * k + i * 28 * k}" cy="${y + bar / 2}" r="${9 * k}" fill="${c}"/>`
)
)
const pw = 320 * k,
ph = 44 * k,
px = x + 155 * k,
py = y + (bar - ph) / 2
s.push(
`<rect x="${half(px)}" y="${half(py)}" width="${pw - 1}" height="${ph - 1}" rx="${8 * k}" fill="${t.panelTop}" stroke="${t.panelStroke}"/>`
)
s.push(
`<g transform="translate(${px + 12 * k} ${py + ph / 2 - 9 * k}) scale(${k})">${icons.lock(0, 0, t.icon)}</g>`
)
s.push(
label(t, px + 36 * k, py + ph / 2, url, {
size: 20 * k,
color: t.textSubtle,
})
)
s.push(body)
return { svg: s.join('\n'), x, y, w, h, contentY: y + bar, k }
}
// Skeleton pieces
export const skel = {
bar: (t, x, y, w, h = 24, color = t.skel) =>
`<rect x="${x}" y="${y}" width="${w}" height="${h}" rx="${Math.min(6, h / 2)}" fill="${color}"/>`,
avatar: (t, cx, cy, r = 28, color = t.skel) =>
`<circle cx="${cx}" cy="${cy}" r="${r}" fill="${color}"/>`,
square: (t, x, y, size = 24, color = t.skel) =>
`<rect x="${x}" y="${y}" width="${size}" height="${size}" rx="${size / 5}" fill="${color}"/>`,
// Image placeholder: tile with a mountain and a sun.
thumb: (t, x, y, w, h, color = t.skel, detail = t.textMuted) => {
const s = Math.min(w, h)
return (
`<rect x="${x}" y="${y}" width="${w}" height="${h}" rx="${s / 8}" fill="${color}"/>` +
`<circle cx="${x + w * 0.32}" cy="${y + h * 0.32}" r="${s * 0.09}" fill="${detail}" opacity="0.6"/>` +
`<path d="M${x + w * 0.12} ${y + h * 0.82} L${x + w * 0.42} ${y + h * 0.5} L${x + w * 0.6} ${y + h * 0.66} L${x + w * 0.72} ${y + h * 0.56} L${x + w * 0.9} ${y + h * 0.82} Z" fill="${detail}" opacity="0.6"/>`
)
},
}
// The page inside a browser window, laid out the way the docs draw it: a
// header row (avatar + title bar), a sidebar of short bars, and a content
// column that shares its top and bottom edges with the sidebar. Everything is
// scaled by the window's `k`. Returns the content rect; fill it per moment
// with `postCard`, `commentRows`, `hole` and `card`.
export function pageLayout(t, win, { sidebar = true } = {}) {
const { x, y, w, h, contentY, k } = win
const pad = 28 * k
const s = []
// header: avatar and a title bar, vertically centered on each other
const r = 14 * k
const hy = contentY + pad + r
s.push(skel.avatar(t, x + pad + r, hy, r))
s.push(
skel.bar(
t,
x + pad + r * 2 + 16 * k,
hy - 8 * k,
w - pad * 2 - r * 2 - 16 * k,
16 * k
)
)
// sidebar and content column
const top = hy + r + 24 * k
const bottom = y + h - pad
const sbW = sidebar ? 110 * k : 0
if (sidebar) {
// a stack of short bars from the top, like a nav list
const widths = [1, 0.75, 0.9, 0.6]
const bh = 14 * k
widths.forEach((f, i) =>
s.push(skel.bar(t, x + pad, top + i * 40 * k, sbW * f, bh))
)
}
const cx = x + pad + sbW + (sidebar ? 24 * k : 0)
const content = { x: cx, y: top, w: x + w - pad - cx, h: bottom - top }
// the usual split of the content column: post on top, comments below
const gap = 12 * k
const postH = Math.round((content.h - gap) * 0.56)
const regions = {
post: { x: cx, y: top, w: content.w, h: postH },
comments: {
x: cx,
y: top + postH + gap,
w: content.w,
h: content.h - postH - gap,
},
}
return { svg: s.join('\n'), content, regions, k }
}
// A post card: outlined card with a title bar and body lines. `color` 'skel'
// draws it as plain rendered UI; an accent name draws it as an accent card
// with the skeleton tinted to match.
export function postCard(t, x, y, w, h, k = 1, color = 'skel') {
const accent = color !== 'skel' ? t[color] : null
const c = accent ? accent.skelOn : t.skel
const pad = 16 * k
const frame = accent
? card(t, x, y, w, h, { color, radius: 8 * k, strokeWidth: 1.5 * k })
: `<rect x="${x}" y="${y}" width="${w}" height="${h}" rx="${8 * k}" fill="none" stroke="${t.panelStroke}" stroke-width="${1.5 * k}"/>`
// title bar plus at most three body lines; the card's height is the caller's
const lines = Math.max(
1,
Math.min(3, Math.floor((h - pad * 2 - 14 * k) / (18 * k)))
)
let body = skel.bar(
t,
x + pad,
y + pad,
Math.min(120 * k, w * 0.45),
14 * k,
c
)
for (let i = 0; i < lines; i++) {
const ly = y + pad + 14 * k + 10 * k + i * 18 * k
if (ly + 8 * k > y + h - pad) break
body += skel.bar(
t,
x + pad,
ly,
(w - pad * 2) * (i === lines - 1 ? 0.6 : 1),
8 * k,
c
)
}
return frame + body
}
// Comment rows: small avatar + one line each, spread evenly over the height.
export function commentRows(
t,
x,
y,
w,
h,
k = 1,
color = 'skel',
rows = 3,
{ frame = color !== 'skel' } = {}
) {
const c = color !== 'skel' ? t[color].skelOn : t.skel
let out = ''
if (frame) {
out += card(t, x, y, w, h, { color, radius: 8 * k, strokeWidth: 1.5 * k })
const pad = 12 * k
x += pad
y += pad
w -= pad * 2
h -= pad * 2
}
const r = 7 * k
const step = rows > 1 ? Math.min(34 * k, (h - r * 2) / (rows - 1)) : 0
const widths = [0.7, 0.45, 0.6]
for (let i = 0; i < rows; i++) {
const cy = y + r + i * step
out += skel.avatar(t, x + r, cy, r, c)
out += skel.bar(
t,
x + r * 2 + 10 * k,
cy - 4 * k,
(w - r * 2 - 10 * k) * widths[i % widths.length],
8 * k,
c
)
}
return out
}
// A region that has not rendered yet. Blue dashed by default; `style: 'gray'`
// gives the Suspense-fallback look. Optional centered label.
export function hole(
t,
x,
y,
w,
h,
{
style = 'blue',
label: text,
radius = 10,
strokeWidth = 2,
dash = '8 5',
labelSize = Math.min(18, h / 3),
} = {}
) {
const c = style === 'gray' ? null : t[style]
const rect = c
? `<rect x="${x}" y="${y}" width="${w}" height="${h}" rx="${radius}" fill="${c.fill}" stroke="${c.stroke}" stroke-width="${strokeWidth}" stroke-dasharray="${dash}"/>`
: `<rect x="${x}" y="${y}" width="${w}" height="${h}" rx="${radius}" fill="none" stroke="${t.panelStroke}" stroke-width="${strokeWidth}" stroke-dasharray="${dash}"/>`
return (
rect +
(text
? label(t, x + w / 2, y + h / 2, text, {
size: labelSize,
weight: 500,
color: c ? c.text : t.textMuted,
anchor: 'middle',
})
: '')
)
}
// A solid accent card (content that has rendered, a highlighted row, a route box).
export function card(
t,
x,
y,
w,
h,
{
color = 'blue',
radius = 10,
dashed = false,
strokeWidth = 2,
dash = '8 5',
label: text,
labelSize = Math.min(18, h / 3),
} = {}
) {
const c = t[color]
return (
`<rect x="${x}" y="${y}" width="${w}" height="${h}" rx="${radius}" fill="${c.fill}" stroke="${c.stroke}" stroke-width="${strokeWidth}"${dashed ? ` stroke-dasharray="${dash}"` : ''}/>` +
(text
? label(t, x + w / 2, y + h / 2, text, {
size: labelSize,
weight: 500,
color: c.text,
anchor: 'middle',
})
: '')
)
}
// ---------------------------------------------------------------------------
// Badges and legends
// Letter badge (A, B, S, D) anchored at its top-left corner.
export function badge(t, x, y, letter, color = 'blue', size = 32) {
const c = t[color]
return (
`<rect x="${x}" y="${y}" width="${size}" height="${size}" rx="${size / 4}" fill="${c.badgeFill}" stroke="${c.stroke}" stroke-width="2"/>` +
label(t, x + size / 2, y + size / 2, letter, {
size: size * 0.6,
weight: 500,
color: c.text,
anchor: 'middle',
})
)
}
// Mono status pill: "Routable", "HARD NAV", "Zone A".
export function statusBadge(
t,
x,
y,
text,
color = 'gray',
{ size = 18, padX = 14, h = 34 } = {}
) {
const c = t[color]
const w = Math.round(textWidth(text, size, { mono: true }) + padX * 2)
return (
`<rect x="${x}" y="${y}" width="${w}" height="${h}" rx="6" fill="${c.badgeFill}" stroke="${c.stroke}" stroke-width="1.5"/>` +
code(t, x + w / 2, y + h / 2, text, {
size,
color: c.text,
anchor: 'middle',
})
)
}
// Legend row: badge + description.
export function legendRow(t, x, y, letter, color, text) {
return (
badge(t, x, y, letter, color, 36) +
label(t, x + 52, y + 18, text, { size: 20, color: t.textMuted })
)
}
// Callout: label with a leader line ending at (tx, ty).
export function callout(
t,
x,
y,
text,
tx,
ty,
{ color = t.arrow, anchor = 'end' } = {}
) {
const lx = anchor === 'end' ? x + 16 : x - 16
return (
label(t, x, y, text, {
size: 22,
weight: 600,
color: t.textSubtle,
anchor,
}) +
`<line x1="${lx}" y1="${y}" x2="${tx}" y2="${ty}" stroke="${color}" stroke-width="2" stroke-linecap="round"/>`
)
}
// ---------------------------------------------------------------------------
// Code panel with a title bar (React icon + file name) and highlighted lines.
// lines: array of arrays of [text, tokenName]; tokenName indexes t.code.
export function codePanel(
t,
x,
y,
w,
title,
lines,
{ lineHeight = 36, size = 20, pad = 28 } = {}
) {
const bar = 54
const h = bar + pad * 2 + lines.length * lineHeight - (lineHeight - size)
const s = [panel(t, x, y, w, h)]
s.push(
`<path d="M${half(x)} ${half(y) + bar} V${half(y) + 10} a10 10 0 0 1 10 -10 H${half(x) + w - 11} a10 10 0 0 1 10 10 V${half(y) + bar} Z" fill="${t.titleBar}"/>`
)
s.push(
`<line x1="${x + 1}" x2="${x + w - 1}" y1="${half(y + bar)}" y2="${half(y + bar)}" stroke="${t.titleBarDivider}"/>`
)
s.push(icons.react(x + 24, y + bar / 2 - 9, t.code.react))
s.push(
label(t, x + 54, y + bar / 2, title, { size: 18, color: t.textSubtle })
)
lines.forEach((tokens, i) => {
const ly = y + bar + pad + i * lineHeight + size / 2
let cx = x + pad
tokens.forEach(([text, kind = 'plain']) => {
s.push(code(t, cx, ly, text, { size, color: t.code[kind] }))
cx += textWidth(text, size, { mono: true })
})
})
return { svg: s.join('\n'), h }
}
// Legend row whose key is a fill style rather than a letter: a small card or
// hole drawn the way the thing it explains is drawn.
// kind: { color, dashed } for a card, or { hole: 'blue' | 'gray' } for a hole.
// `k` scales every size for canvases narrower than 1600 (k = width / 1600).
// Its width is 60k + textWidth(text, 20k) when several sit in one row.
export function swatchLegend(t, x, y, kind, text, { k = 1 } = {}) {
const sw = kind.hole
? hole(t, x, y, 44 * k, 24 * k, {
style: kind.hole,
radius: 6 * k,
strokeWidth: 2 * k,
dash: `${8 * k} ${5 * k}`,
})
: card(t, x, y, 44 * k, 24 * k, {
color: kind.color ?? 'blue',
dashed: !!kind.dashed,
radius: 6 * k,
strokeWidth: 2 * k,
dash: `${8 * k} ${5 * k}`,
})
return (
sw +
label(t, x + 60 * k, y + 12 * k, text, { size: 20 * k, color: t.textMuted })
)
}
// ---------------------------------------------------------------------------
// Grid: column headers across the top (stages, moments, variants), a label
// column on the left (one per row), faint dashed dividers between columns.
// Draw the cells yourself with `card` / `hole` from the returned geometry:
// const g = grid(t, x, y, { columns, rows }); g.span(row, fromCol, toCol) -> { x, y, w, h }
// To line the columns up with a row of windows above: colW = windowW + gap,
// inset = gap / 2, x = first window's x - labelW - gap - gap / 2, and
// y = window bottom + 16 * k. The column headers then sit under the windows
// and double as their captions. The dividers extend `inset` beyond the first
// and last window on each side; include that when centering the block.
//
// columns: [{ title, subtitle, subtitleMono }] rows: [{ label, mono = true, muted }]
export function grid(
t,
x,
y,
{
columns,
rows,
k = 1, // scales every default below and the text (k = width / 1600)
labelW = 200 * k,
labelHeader,
labelHeaderMono = true,
colW = 260 * k,
rowH = 56 * k,
rowGap = 20 * k,
headerH = (columns.some((c) => c.subtitle) ? 70 : 48) * k,
gap = 40 * k, // between the label column and the first column
inset = 10 * k, // cell inset from the column dividers
}
) {
const s = []
const colX = (i) => x + labelW + gap + i * colW
const rowY = (r) => y + headerH + r * (rowH + rowGap)
const h = headerH + rows.length * rowH + (rows.length - 1) * rowGap
const w = labelW + gap + columns.length * colW
// Header text is centered 12px below `y` so its cap height starts at `y`;
// the dividers end at the last row, so [y, y + h] is the visual box.
if (labelHeader)
s.push(
(labelHeaderMono ? code : label)(t, x + labelW, y + 12 * k, labelHeader, {
size: 18 * k,
color: t.textMuted,
anchor: 'end',
})
)
columns.forEach((c, i) => {
const cx = colX(i) + colW / 2
s.push(
label(t, cx, y + 12 * k, c.title, {
size: 20 * k,
weight: 600,
color: t.textSubtle,
anchor: 'middle',
})
)
if (c.subtitle)
s.push(
(c.subtitleMono ? code : label)(t, cx, y + 42 * k, c.subtitle, {
size: 15 * k,
color: t.textMuted,
anchor: 'middle',
})
)
})
for (let i = 0; i <= columns.length; i++) {
const dx = half(colX(i))
s.push(
`<line x1="${dx}" x2="${dx}" y1="${y + headerH - 10 * k}" y2="${y + h}" stroke="${t.divider}" stroke-dasharray="${4 * k} ${4 * k}"/>`
)
}
rows.forEach((r, i) => {
const cy = rowY(i) + rowH / 2
s.push(
(r.mono === false ? label : code)(t, x + labelW, cy, r.label, {
size: 20 * k,
color: r.muted ? t.textMuted : t.text,
anchor: 'end',
})
)
})
return {
svg: s.join('\n'),
w,
h,
colX,
rowY,
span: (r, from, to = from) => ({
x: colX(from) + inset,
y: rowY(r),
w: (to - from + 1) * colW - inset * 2,
h: rowH,
}),
}
}
#!/usr/bin/env python3
"""Ink margins of a rendered diagram, in CSS px (the PNGs are 2x).
Usage: python3 measure.py light/<name>.png [dark/<name>.png ...]
Counts a pixel as ink when it differs from the background by more than a
threshold, which skips the grid; panel shadows still count at the bottom,
so expect the bottom margin to read a few px smaller than the top.
"""
import sys
from PIL import Image
THRESHOLD = 40
for path in sys.argv[1:]:
im = Image.open(path).convert('RGB')
w, h = im.size
bg = im.getpixel((0, 0))
px = im.load()
def ink(x, y):
p = px[x, y]
return abs(p[0] - bg[0]) + abs(p[1] - bg[1]) + abs(p[2] - bg[2]) > THRESHOLD
cols = [x for x in range(w) if any(ink(x, y) for y in range(0, h, 2))]
rows = [y for y in range(h) if any(ink(x, y) for x in range(0, w, 2))]
if not cols or not rows:
print(f'{path}: no ink found'); continue
left, right = cols[0] / 2, (w - 1 - cols[-1]) / 2
top, bottom = rows[0] / 2, (h - 1 - rows[-1]) / 2
print(f'{path}: left {left:g} right {right:g} top {top:g} bottom {bottom:g} (canvas {w // 2}x{h // 2})')
#!/usr/bin/env bash
# Render every diagram module in ./diagrams to light/<name>.png and dark/<name>.png at 2x.
#
# Usage: copy lib.mjs, gen.mjs, diagrams/ and this script into a scratch folder,
# add or edit a module in diagrams/, then run ./render.sh from that folder.
# Set CHROME=/path/to/chrome when Chrome is not installed at the default macOS path.
set -euo pipefail
CHROME="${CHROME:-/Applications/Google Chrome.app/Contents/MacOS/Google Chrome}"
cd "$(dirname "$0")"
rm -f ./*.html light/*.png dark/*.png light/*.svg dark/*.svg
node gen.mjs
for svg in light/*.svg; do
name="$(basename "$svg" .svg)"
height="$(node -e "const s=require('fs').readFileSync('$svg','utf8');console.log(/height=\"(\d+)\"/.exec(s)[1])")"
width="$(node -e "const s=require('fs').readFileSync('$svg','utf8');console.log(/width=\"(\d+)\"/.exec(s)[1])")"
for theme in light dark; do
"$CHROME" --headless=new --disable-gpu --hide-scrollbars \
--force-device-scale-factor=2 \
--window-size="$width,$height" \
--virtual-time-budget=4000 \
--screenshot="$PWD/$theme/$name.png" \
"file://$PWD/$name-$theme.html" 2>/dev/null
echo "rendered $theme/$name.png ($((width * 2))x$((height * 2)))"
done
done
# Style tokens
Measured from published docs diagrams of every kind listed in SKILL.md. All values are CSS px on a 1600-wide canvas; `lib.mjs` holds the same values in its `themes` object. Use the token, not a new hex.
## Canvas
| Property | Value |
| ---------- | -------------------------------------------------------------------------------------------------------------------------------------- |
| Width | 1600 (render at 2x → 3200). Match the width the mdx declares if a page uses another. |
| Height | per diagram, declared in the mdx |
| Background | light `#FBFBFB`, dark `#0D0D0D` |
| Grid | 40px squares, 1px lines, light `#F7F7F7`, dark `#161616`, an SVG `<pattern>` over the bg |
| Margins | about 60 when the height is yours to choose; equal top/bottom and equal left/right always. Center the whole block, never left-align it |
## Colors
| Token | Light | Dark | Used for |
| ----------------------------------- | ------------------------------------------------------------------------------------------------ | ----------------------------------- | --------------------------------------------------- |
| `panelTop` → `panelBottom` | `#FFFFFF` → `#F9F9F9` | `#313131` → `#282828` | vertical gradient on every panel and window |
| `panelStroke` | `#D9D9D9` | `#484848` | 1px panel, pill and card borders |
| `panelMuted` | `#F1F1F1` | `#1F1F1F` | gray-filled rows and pills (elided, not routable) |
| `divider` | `#E8E8E8` | `#434343` | 1px lines between rows |
| `shadow` | `rgba(0,0,0,0.08)` | `rgba(0,0,0,0.5)` | blurred rect under panels, offset 6px |
| `titleBar` / `titleBarDivider` | `#F7F7F7` / `#E3E3E3` | `#232323` / `#3A3A3A` | browser and code panel title bars |
| `text` | `#2E2E2E` | `#D4D4D4` | labels in trees and pills |
| `textSubtle` | `#616161` | `#8F8F8F` | URL in the window bar, code panel title, callouts |
| `textMuted` | `#8F8F8F` | `#A1A1A1` | captions, legend text, muted rows |
| `icon` / `iconMuted` | `#9A9A9A` / `#CECECE` | `#888888` / `#555555` | folder, file, globe, lock glyphs |
| `arrow` | `#A8A8A8` | `#878787` | arrows, brackets, bracket captions |
| `skel` | `#C9C9C9` | `#4A4A4A` | skeleton bars, avatars, squares, image placeholders |
| `blue.stroke` / `.fill` / `.text` | `#0070F3` / `#D5E6FA` / `#0067D6` | `#0A72EF` / `#10233D` / `#52A8FF` | the primary accent |
| `blue.dot` | `#197DF3` | `#0761C9` | the "this file" marker in trees |
| `blue.skelOn` / `.thumbOn` | `#A8B9CD` / `#C1D2E5` | `#2F4A6E` / `#1E3657` | skeleton inside a blue region |
| `purple.stroke` / `.fill` / `.text` | `#8E4EC6` / `#EAE0F2` / `#793AAF` | `#9A5CD0` / `#2A1F38` / `#C4A1E6` | second accent (static regions, zone C, slot B) |
| `red.stroke` / `.fill` / `.text` | `#E5484D` / `#F7DFE0` / `#CA2A30` | same stroke / `#3A1D1F` / `#F08A8E` | negative badges, zone B |
| `green.stroke` / `.fill` / `.text` | `#46A758` / `#DCEBDF` / `#46A758` | same stroke / `#1B2E1F` / `#6FCB80` | positive badges |
| `gray.stroke` / `.fill` / `.text` | `#8F8F8F` / `#DEDEDE` / `#666666` | `#6F6F6F` / `#2A2A2A` / `#B0B0B0` | neutral mono pills (`SOFT NAV`) |
| `static.stroke` / `.fill` / `.text` | `#C9C9C9` / `#F1F1F1` / `#666666` | `#4A4A4A` / `#1F1F1F` / `#B0B0B0` | a static / prerendered region in a bar or grid cell |
| `code.*` | GitHub Light: tag `#005CC5`, attr `#6F42C1`, keyword `#D73A49`, ident `#E36209`, punct `#909295` | GitHub Dark equivalents | code panels |
| `code.react` | `#61DAFB` | same | React logo in code panel titles |
| `trafficLights` | `#FF6059` `#FFBD2E` `#28CA42` | same | the three window dots |
## What the colors mean
The docs use color as a legend, so keep the meaning stable across a diagram and consistent with its neighbours:
- **Gray**: static, prerendered, already there, or not the focus. Skeleton UI is always gray unless it sits inside an accent region. A static _region_ in a bar or grid cell is a stroked `static` card (`panelMuted` fill, `skel` stroke), so it has the same weight as the accent cards beside it; the darker `gray` accent is for mono pills.
- **Blue, dashed stroke + fill**: not included in static output at this stage; can render at request time (a Suspense hole, "request-time content").
- **Blue, solid stroke + fill**: content that has rendered, arrived, or is highlighted as the subject (streamed card, selected `<Link>`, slot A).
- **Gray, dashed stroke, no fill**: a Suspense fallback standing in for content.
- **Purple**: a second category next to blue (static vs dynamic regions, slot B, zone C), never a second shade of request-time content.
- **Red / green**: judgments (not routable / routable). Only in badges and zone boxes.
Within one picture every accent means exactly one thing, and the same thing in every part of the picture. Rendered UI inside a window stays gray skeleton regardless; only the state the picture is about gets the accent.
## Typography
| Text | Font | Size | Weight | Notes |
| ------------------------- | ---------- | ---- | ------ | ---------------------------------------------------------- |
| Tree rows, URL pills | Inter | 20 | 400 | 600 for the highlighted row; `dominant-baseline="central"` |
| Captions, legend text | Inter | 20 | 400 | `textMuted` |
| Callout labels | Inter | 22 | 600 | `textSubtle`, leader line in the region's accent |
| Window URL | Inter | 20 | 400 | `textSubtle`, after a lock glyph; scales with the window |
| Stage / column captions | Inter | 16 | 500 | `textMuted`, centered under the thing they name |
| Code panel body | Geist Mono | 20 | 400 | 36px line height |
| Mono pills, status badges | Geist Mono | 18 | 400 | centered |
| Letter badges | Inter | 19 | 500 | in a 32px rounded square |
Inter comes from Google Fonts in the HTML wrapper (`display=block` so Chrome waits for it). Geist Mono must be installed locally (`~/Library/Fonts/GeistMono-*.otf`); if it is missing the fallback `ui-monospace` is acceptable but say so when you hand off.
## Anatomy
**Panel**: radius 10, 1px `panelStroke` snapped to the half pixel, `panelTop→panelBottom` gradient, shadow rect offset 6px blurred 8px.
**Tree row**: 80 tall, 32px side padding, 18px icon, text 32px after the icon, 40px indent per depth, 1px `divider` between rows. Blue dot: 10px radius with a 16px radius `blue.fill` glow, 42px from the right edge. Muted row: `panelMuted` fill, muted icon and text.
**URL pill**: a one-row panel, globe at 32px, path at 64px. Stack several in one panel with dividers when they belong to one tree.
**Arrow**: 2px, round caps, open chevron head 10px long and 14px tall. Gray by default; blue when it carries streamed content. Bracket arrows beside a tree have a 10px corner radius and the same head.
**Browser window**: reference size 527×476. Title bar 70 tall, traffic lights radius 9 at 37/65/93px, URL pill 320×44 radius 8 starting at 155px. All of it scales with the width you pass (`k = w / 527`).
**Skeleton**: bars 24 tall radius 6, avatar radius 28, image placeholder is a tile with a sun and a mountain in `textMuted` at 60% opacity. Placeholders stand for real UI, so they keep real proportions: an avatar is a circle no taller than the row it sits in, bars have at least their own height of space between them, nothing touches a neighbour or the window edge.
**Page inside a window** (`pageLayout`): 28px padding at `k = 1`. Header row: avatar radius 14 and a 16px title bar centered on it, 16px apart. 24px below, a 110px-wide sidebar of four 14px bars (widths 1 / 0.75 / 0.9 / 0.6) spread evenly from the content's top edge to its bottom edge, then 24px, then the content column to the right padding. Content is a `postCard` (outlined card, 16px padding, 14px title bar, 8px body lines 18px apart) and `commentRows` (7px avatars with one 8px line each), or a `hole` / `card` spanning the same rect when that content is not there yet. Everything scales with the window's `k`.
**Hole**: 2px dashed stroke `8 5`, radius 10, fill from the accent. Optional centered label at `min(18, h/3)`. Scale `strokeWidth`, `dash` and `labelSize` down inside small windows.
**Badges**: letter badge 32px square, radius 8, 2px accent stroke, `badgeFill`. Status pill 34 tall, radius 6, 1.5px stroke, mono text.
**Grid**: column headers 20px/600 `textSubtle` with optional 15px subtitles (header 70 tall with subtitles, 48 without), a right-aligned mono label column, dashed `divider` lines between columns, rows 56 tall with 20px gaps, cells inset 10px from the dividers. All defaults scale with `k`. Cells are `card` / `hole` spans; a `swatchLegend` explains fill styles when the cells carry no text. Under a row of windows, the grid starts 16px below them.
**Text metrics**: there are no font metrics at generation time. `textWidth(str, size, { mono })` is the heuristic (0.52 × size per character for Inter, 0.58 for Geist Mono); size blocks with it rather than a new constant, then measure.
**Code panel**: 54px title bar with the React logo and a file name, 28px padding, 36px lines.
## Crispness
Snap every 1px stroke to a `.5` coordinate (`x + 0.5`, `width - 1`). Leave 1.5px and 2px strokes on integers. Render with `--force-device-scale-factor=2` and `--hide-scrollbars`.
......@@ -10,8 +10,6 @@ related:
- app/guides/optimizing-prefetching
- app/api-reference/config/next-config-js/partialPrefetching
- app/api-reference/file-conventions/route-segment-config/prefetch
- app/api-reference/functions/prefetch
- app/api-reference/functions/navigation
---
[Partial Prefetching](/docs/app/glossary#partial-prefetching) changes what a `<Link>` downloads for a Cache Components route. With Partial Prefetching enabled, a `<Link>` prefetches the route's [App Shell](/docs/app/glossary#app-shell): its static content and the cached content that doesn't depend on the URL. Next.js builds one App Shell per route and reuses it for every link to that route, rather than prefetching each link separately as it did before.
......@@ -46,7 +44,6 @@ To adopt an existing app by hand:
2. [Enable `partialPrefetching`](#enable-partial-prefetching). For larger migrations, you can [adopt incrementally](#adopting-incrementally) with the global flag off. The [dynamic data during prefetching](/docs/messages/instant-link-prefetch-partial) insight identifies each destination that still uses the legacy full prefetch.
3. [Move URL data behind Suspense](#move-url-data-behind-suspense), resolving the [URL data outside of Suspense](/docs/messages/instant-shell-url-data) insight.
4. Optionally, [prefetch URL data](#prefetching-url-data) on the routes where streaming in after navigation isn't enough.
5. Optionally, [exclude cached content from a prefetch](/docs/app/guides/optimizing-prefetching#exclude-content-from-a-prefetch) on the routes where caching content into the App Shell made it heavier than you want.
Both insights are development-only and never block the build. They appear in the dev overlay with fix cards that link the docs page for each fix. If a route isn't ready to adopt, export [`instant = false`](/docs/app/api-reference/file-conventions/route-segment-config/instant) from its page or layout to opt the route out of instant-navigation validation, and return to it later.
......
......@@ -52,7 +52,7 @@ We'll build a product catalog with category layouts and product detail pages usi
### Prepare your routes
Use [`generateStaticParams`](/docs/app/api-reference/functions/generate-static-params) to define which param values to prerender. When rendering these routes, the param values are known at build time. The prerender process builds a static shell until it hits runtime APIs or uncached data. See [Prerendering](/docs/app/getting-started/caching#prerendering) for more details.
Use [`generateStaticParams`](/docs/app/api-reference/functions/generate-static-params) to define which param values to prerender. When rendering these routes, the param values are known at build time. The prerender process builds a static shell until it reaches a [Request-time API](/docs/app/glossary#request-time-apis) or uncached data. See [Prerendering](/docs/app/getting-started/caching#prerendering) for more details.
The category layout prerenders two categories:
......@@ -176,9 +176,7 @@ export async function getPopularProducts(category: string) {
}
```
If your components access runtime APIs like `cookies` or `headers`, wrap them in `<Suspense>`. Their fallback UI is included in the static shell instead.
{/* TODO: show how unstable_navigation() can help keep content out of the prefetch={true} */}
If a component accesses a Request-time API such as `cookies()` or `headers()`, wrap it in `<Suspense>`. During prerendering, Next.js includes the nearest fallback in the static shell. To keep the component out of a `<Link prefetch={true}>` as well, await [`navigation()`](/docs/app/api-reference/functions/navigation) before the request-time access. See [Keep the prefetch static](/docs/app/guides/optimizing-prefetching#keep-the-prefetch-static).
### At build time
......@@ -208,12 +206,16 @@ Links to these pages need `prefetch={true}`. A default `<Link>` prefetches only
> **Good to know**: The App Shell for unlisted params is served from Next.js 16.3. Earlier versions wait for a full server render before sending the response.
### Wait for complete static output
For an unlisted parameter, [`ensureStatic = 'navigation'`](/docs/app/api-reference/file-conventions/route-segment-config/ensureStatic#navigation) makes the first request wait for the complete static page. Without this requirement, Next.js can return a prerendered fallback while it generates the page in the background. Next.js stores the completed page for later requests.
### What the upgrade produces
After the first visit, Next.js renders the page in the background with the known params and tries to push the static boundary as far down the component tree as possible:
- If every data access is cached and all params are resolved, the upgrade produces a **fully static page**.
- If all params are resolved but the render still hits uncached data or runtime APIs (`cookies`, `headers`) wrapped in `<Suspense>` boundaries, the upgrade produces a **cached page with those fallbacks**. The uncached or runtime parts stream in at request time.
- If all params are resolved but the render still reaches uncached data or Request-time APIs (`cookies()`, `headers()`) wrapped in `<Suspense>` boundaries, the upgrade produces a **cached page with those fallbacks**. The uncached or request-specific parts stream in at request time.
- Params are resolved in route order. A param value not returned by `generateStaticParams` stays unresolved and prevents any deeper params from upgrading.
## Choosing what to prerender
......@@ -226,6 +228,8 @@ Instead, use [`generateStaticParams`](/docs/app/api-reference/functions/generate
If you are migrating from the Pages Router:
{/* <!-- TODO(param-matching): Map all these to the appropriate param matching API value. --> */}
- `fallback: true` in `getStaticPaths` maps to Cache Components with Partial Prefetching. Visitors get a `<Suspense>` fallback instantly, and Next.js stores the completed route for subsequent visits.
- [`fallback: 'blocking'`](https://nextjs.org/docs/pages/api-reference/functions/get-static-paths#fallback-blocking) maps to Cache Components without Partial Prefetching. Await `params` outside `<Suspense>` so the first request waits for the completed route, which Next.js then stores for subsequent visits.
- `router.isFallback` is not needed. The prerendering step generates a static shell, and you can grow it further with `'use cache'`.
......
---
title: Keeping pages static
description: Keep selected route output static as your app changes.
nav_title: Keeping pages static
related:
title: API reference
description: Require static output across a route or defer work within one subtree.
links:
- app/api-reference/file-conventions/route-segment-config/ensureStatic
- app/api-reference/functions/prefetch
- app/api-reference/functions/navigation
---
Before [Cache Components](/docs/app/api-reference/config/next-config-js/cacheComponents), route segment configs such as [`dynamic = 'force-static'`](/docs/app/guides/caching-without-cache-components#dynamic), `dynamic = 'force-dynamic'`, and `dynamic = 'error'` selected a rendering mode for an entire route. Cache Components lets one route combine prerendered UI, cached content, and request-specific content rendered at request time.
This flexibility is useful for routes that need personalization. Use [`ensureStatic`](/docs/app/api-reference/file-conventions/route-segment-config/ensureStatic) when some or all of a route must avoid request-time server rendering for predictable performance and compute costs.
## Decide what should stay static
Static output does not depend on request-specific data. Next.js can generate it before a request and reuse it across requests.
With [Partial Prefetching](/docs/app/api-reference/config/next-config-js/partialPrefetching), route output becomes available in three [navigation stages](/docs/app/glossary#navigation-stages):
1. A default `<Link>` loads the [App Shell](/docs/app/glossary#app-shell).
2. `<Link prefetch={true}>` can also load content for that link's URL.
3. The navigation renders anything that remains after the click.
Each `ensureStatic` level extends the static requirement through one of these stages. In the following diagram, gray marks static output and blue marks content that can render at request time:
<Image
alt="The Shell, Prefetch, and Navigation stages, with bars showing how each ensureStatic value extends the static requirement through those stages"
srcLight="/docs/light/ensure-static-visual.png"
srcDark="/docs/dark/ensure-static-visual.png"
width="1200"
height="530"
/>
Choose a level based on which request must use only static output:
- `'shell'`: the App Shell loaded by a default `<Link>`.
- `'prefetch'`: the App Shell and the [per-link prefetch](/docs/app/guides/optimizing-prefetching) from `<Link prefetch={true}>`, which can include content for the link's [URL data](/docs/app/glossary#url-data), such as `params`.
- `'navigation'`: the complete route, including the response returned after the user navigates.
## Example
The following example adds static requirements to three parts of an online store: its shared cart, product pages, and public buying guides.
```txt
app/
├── store/
│ ├── layout.tsx # Shared layout with the cart
│ ├── page.tsx # Product catalog
│ └── products/
│ └── [slug]/
│ └── page.tsx # Product details and cart status
├── guides/
│ └── [id]/
│ └── page.tsx # Editorial buying guides
└── ui/
├── cart.tsx
└── product.tsx
lib/
└── guides.ts
```
Enable [Cache Components](/docs/app/api-reference/config/next-config-js/cacheComponents) and [Partial Prefetching](/docs/app/api-reference/config/next-config-js/partialPrefetching):
```ts filename="next.config.ts" highlight={4,5}
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
cacheComponents: true,
partialPrefetching: true,
}
export default nextConfig
```
### Step 1: Load a static App Shell
The shared store layout displays a visitor's cart count. `CartButton` reads the count from a cookie on the server:
```tsx filename="app/ui/cart.tsx"
import { cookies } from 'next/headers'
export async function CartButton() {
const value = Number((await cookies()).get('cart-count')?.value ?? 0)
return <button>Cart ({value})</button>
}
```
The layout places `CartButton` inside `<Suspense>`, which provides a static fallback while the current count renders:
```tsx filename="app/store/layout.tsx"
import Link from 'next/link'
import { Suspense } from 'react'
import { CartButton } from '@/app/ui/cart'
export default function StoreLayout({ children }: LayoutProps<'/store'>) {
return (
<>
<nav>
<Link href="/store">Products</Link>
<Link href="/guides">Buying guides</Link>
<Suspense fallback={<button>Cart (0)</button>}>
<CartButton />
</Suspense>
</nav>
<main>{children}</main>
</>
)
}
```
The navigation and cart fallback are shared across visitors. Loading a link to the store should not render the personalized cart count on the server before the user clicks. Add `ensureStatic = 'shell'` to make a default `<Link>` request only the static App Shell:
```tsx filename="app/store/layout.tsx" highlight={5}
import Link from 'next/link'
import { Suspense } from 'react'
import { CartButton } from '@/app/ui/cart'
export const ensureStatic = 'shell'
export default function StoreLayout({ children }: LayoutProps<'/store'>) {
// ...
}
```
A default `<Link>` into the store now loads the navigation and `Cart (0)` fallback from static output. The server does not render the current cart count until a later per-link prefetch or navigation requests it. This avoids request-time server work for links that the user may never click.
> **Good to know**: If only `CartButton` needed to be deferred from the App Shell, you could call [`await prefetch()`](/docs/app/api-reference/functions/prefetch) inside that subtree. Here, the requirement applies to the entire store shell, including future changes, so the layout uses `ensureStatic = 'shell'`.
### Step 2: Prefetch static product details
Each product page combines details that can be reused across visitors with a cart action that depends on the current visitor. `ProductDetails` caches its query with [`use cache`](/docs/app/api-reference/directives/use-cache), while `ProductCartStatus` reads a cookie to check whether the product is already in the cart:
```tsx filename="app/ui/product.tsx"
import { cookies } from 'next/headers'
import { db } from '@/lib/db'
type Params = Promise<{ slug: string }>
export async function ProductDetails({ params }: { params: Params }) {
const { slug } = await params
const product = await getProduct(slug)
return <h1>{product.name}</h1>
}
export async function ProductCartStatus({ params }: { params: Params }) {
const { slug } = await params
const cart = (await cookies()).get('cart')?.value?.split(',') ?? []
return (
<button>{cart.includes(slug) ? 'Remove from cart' : 'Add to cart'}</button>
)
}
async function getProduct(slug: string) {
'use cache'
return db.product.findUniqueOrThrow({ where: { slug } })
}
```
The product route prerenders the catalog's product URL with [`generateStaticParams()`](/docs/app/api-reference/functions/generate-static-params). Separate `<Suspense>` boundaries let the product details render with a static cart fallback:
```tsx filename="app/store/products/[slug]/page.tsx"
import { Suspense } from 'react'
import { ProductCartStatus, ProductDetails } from '@/app/ui/product'
export function generateStaticParams() {
return [{ slug: 'coffee-grinder' }]
}
export default function ProductPage({
params,
}: PageProps<'/store/products/[slug]'>) {
return (
<>
<Suspense fallback={<p>Loading product...</p>}>
<ProductDetails params={params} />
</Suspense>
<Suspense fallback={<button>Add to cart</button>}>
<ProductCartStatus params={params} />
</Suspense>
</>
)
}
```
A default product link loads the App Shell, which contains the product fallback. Because the product details are already prerendered, the catalog can include them before the click by setting `prefetch={true}`:
```tsx filename="app/store/page.tsx"
<Link href="/store/products/coffee-grinder" prefetch={true}>
Coffee grinder
</Link>
```
Each visible `prefetch={true}` link can render `ProductCartStatus` to personalize the cart action for that product. A grid with 20 visible products can therefore trigger 20 request-time server renders before the user clicks a product.
Add `ensureStatic = 'prefetch'` to make every product prefetch use only static output:
```tsx filename="app/store/products/[slug]/page.tsx" highlight={4}
import { Suspense } from 'react'
import { ProductCartStatus, ProductDetails } from '@/app/ui/product'
export const ensureStatic = 'prefetch'
export default function ProductPage({
params,
}: PageProps<'/store/products/[slug]'>) {
// ...
}
```
Each product prefetch now includes the cached product details and the static **Add to cart** fallback without invoking request-time server rendering. The current cart status renders after the user follows the link.
An `ensureStatic` value covers the whole route, including layouts above the segment that exports it. On product routes, `'prefetch'` also keeps the store layout static through the per-link prefetch.
> **Good to know**: If only `ProductCartStatus` needed to be deferred from per-link prefetches, you could call [`await navigation()`](/docs/app/api-reference/functions/navigation) before reading the cookie. Here, every product prefetch must avoid request-time server rendering, so the page uses `ensureStatic = 'prefetch'`.
### Step 3: Prerender the buying guides
The store also has public buying guides. Each guide reads its content from the database and applies a theme from a cookie:
```tsx filename="app/guides/[id]/page.tsx"
import { Suspense } from 'react'
import { cookies } from 'next/headers'
import { getGuide } from '@/lib/guides'
export default function GuidePage({ params }: PageProps<'/guides/[id]'>) {
return (
<Suspense fallback={<p>Loading guide...</p>}>
<Guide params={params} />
</Suspense>
)
}
async function Guide({ params }: { params: Promise<{ id: string }> }) {
const { id } = await params
const guide = await getGuide(id)
const theme = (await cookies()).get('theme')?.value
return <article data-theme={theme}>{guide.content}</article>
}
```
The existing `getGuide()` helper performs the database query:
```ts filename="lib/guides.ts"
import { db } from '@/lib/db'
export async function getGuide(id: string) {
return db.guide.findUniqueOrThrow({ where: { id } })
}
```
`next build` currently produces partial prerenders for the store routes and the buying guides:
```text filename="Terminal"
Route (app)
├ /guides/[id]
│ └ ◐ /guides/[id]
├ ◐ /store
└ /store/products/[slug]
├ ◐ /store/products/[slug]
└ ◐ /store/products/coffee-grinder
◐ (Partial Prerender) prerendered as static HTML with dynamic server-streamed content
```
Partial output is expected for the store and product routes because their request-specific cart UI renders later. The buying guides are public editorial pages, so they should return complete static output without request-time server rendering. Add `ensureStatic = 'navigation'`:
```diff filename="app/guides/[id]/page.tsx"
import { Suspense } from 'react'
import { cookies } from 'next/headers'
+ export const ensureStatic = 'navigation'
export default function GuidePage({ params }) {
// ...
}
```
When running `next build` again, Next.js first reports that the dynamic route does not provide any parameter values to prerender:
```bash filename="Terminal"
Error: Page "/guides/[id]": `ensureStatic = "navigation"` requires an exported `generateStaticParams()` function.
Learn more: https://nextjs.org/docs/messages/generate-static-params#with-ensurestatic
at ignore-listed frames
> Build error occurred
Error: Failed to collect page data for /guides/[id]
```
Export `generateStaticParams()` and return at least one buying guide ID. Next.js prerenders the returned IDs during the build. It can generate other allowed IDs on their first request and store the result for later requests. With `'navigation'`, that first request waits for the complete static page instead of streaming a fallback. See [ISR with Cache Components](/docs/app/guides/incremental-static-regeneration-cache-components#at-runtime).
Add a helper that returns the guide IDs to prerender:
```ts filename="lib/guides.ts"
export async function getGuideIds() {
const guides = await db.guide.findMany({ select: { id: true } })
return guides.map(({ id }) => id)
}
```
```tsx filename="app/guides/[id]/page.tsx" highlight={3,7-10}
import { Suspense } from 'react'
import { cookies } from 'next/headers'
import { getGuide, getGuideIds } from '@/lib/guides'
export const ensureStatic = 'navigation'
export async function generateStaticParams() {
const ids = await getGuideIds()
return ids.map((id) => ({ id }))
}
export default function GuidePage({ params }: PageProps<'/guides/[id]'>) {
return (
<Suspense fallback={<p>Loading guide...</p>}>
<Guide params={params} />
</Suspense>
)
}
async function Guide({ params }: { params: Promise<{ id: string }> }) {
const { id } = await params
const guide = await getGuide(id)
const theme = (await cookies()).get('theme')?.value
return <article data-theme={theme}>{guide.content}</article>
}
```
`generateStaticParams()` provides the parameter values, but the guide still contains uncached and request-specific work. The next build reports that the route cannot be fully static:
```bash filename="Terminal"
Error: Route "/guides/[id]": Next.js encountered uncached or runtime data on a route that must be fully static.
This route is configured to be fully static, but uncached or runtime data prevents it from being fully prerendered.
Ways to fix this:
- [cache] For uncached data (`fetch`, database calls): cache the access with `"use cache"` (does not apply to `connection()`)
- [remove] Remove the data access
- [client] Read the data on the client
Learn more: https://nextjs.org/docs/messages/static-route-dynamic
at Suspense (<anonymous>)
at body (<anonymous>)
at html (<anonymous>)
```
The build identifies the affected route, but its stack frames do not include source locations for the data access. To get source-mapped code frames while fixing it, start `next dev` and open `/guides/coffee`. If you can only run a build, use [`next build --debug-prerender`](/docs/app/guides/building#debug-prerender-errors).
The development overlay first points to the uncached database query:
```ts filename="lib/guides.ts" highlight={1}
return db.guide.findUniqueOrThrow({ where: { id } })
```
It presents three ways to handle uncached data:
<FixCardGrid>
<FixCard
group="cache"
title="Cache the data"
href="/docs/messages/static-route-dynamic#cache-the-data"
snippets={[
{ text: 'async function getData() {' },
{ text: ' "use cache"', highlight: true },
{ text: ' return await db.query(…)' },
]}
/>
<FixCard
group="remove"
title="Remove the data access"
href="/docs/messages/static-route-dynamic#remove-the-data-access"
snippets={[
{ text: 'async function Page() {' },
{ text: '- await connection()', highlight: true },
{ text: ' return <Content />' },
]}
/>
<FixCard
group="client"
title="Read the data on the client"
href="/docs/messages/static-route-dynamic#read-the-data-on-the-client"
snippets={[
{ text: "'use client'" },
{ text: "const data = useSWR('/api')", highlight: true },
{ text: 'return <Content data={data} />' },
]}
/>
</FixCardGrid>
The buying-guide content can be shared across visitors, so the **Cache** fix preserves the page's static requirement. Add the [`'use cache'` directive](/docs/app/api-reference/directives/use-cache) to `getGuide()` so Next.js can reuse the query result:
```ts filename="lib/guides.ts" highlight={9}
import { db } from '@/lib/db'
export async function getGuideIds() {
const guides = await db.guide.findMany({ select: { id: true } })
return guides.map(({ id }) => id)
}
export async function getGuide(id: string) {
'use cache'
return db.guide.findUniqueOrThrow({ where: { id } })
}
```
After the query is cached, the overlay points to the remaining request-specific value:
```tsx filename="app/guides/[id]/page.tsx" highlight={1}
const theme = (await cookies()).get('theme')?.value
```
The overlay now presents the fixes for runtime data:
<FixCardGrid>
<FixCard
group="remove"
title="Remove the data access"
href="/docs/messages/static-route-runtime#remove-the-data-access"
snippets={[
{ text: 'async function Page() {' },
{ text: '- const store = await cookies()', highlight: true },
{ text: ' return <Content />' },
]}
/>
<FixCard
group="client"
title="Read the data on the client"
href="/docs/messages/static-route-runtime#read-the-data-on-the-client"
snippets={[
{ text: "'use client'" },
{ text: "use(browser('Read cookie'))", highlight: true },
{ text: 'document.cookie.match(/cart=/)' },
]}
/>
</FixCardGrid>
The buying guides do not need a visitor-specific theme, so remove the cookie access:
```diff filename="app/guides/[id]/page.tsx"
import { Suspense } from 'react'
- import { cookies } from 'next/headers'
import { getGuide, getGuideIds } from '@/lib/guides'
// ...
async function Guide({ params }) {
const { id } = await params
const guide = await getGuide(id)
- const theme = (await cookies()).get('theme')?.value
- return <article data-theme={theme}>{guide.content}</article>
+ return <article>{guide.content}</article>
}
```
With the database query cached and the request-specific theme removed, `next build` produces a complete static page for the listed guide:
```text filename="Terminal"
Route (app)
├ /guides/[id]
│ ├ ◐ /guides/[id]
│ └ ○ /guides/coffee
├ ◐ /store
└ /store/products/[slug]
├ ◐ /store/products/[slug]
└ ◐ /store/products/coffee-grinder
○ (Static) prerendered as static content
◐ (Partial Prerender) prerendered as static HTML with dynamic server-streamed content
```
The listed guide is now fully prerendered. For an unlisted guide ID, the first request waits while Next.js generates and stores the complete static page. The buying guides no longer perform request-time server rendering, and `ensureStatic` will report future changes that would break that requirement.
The store now loads shared navigation from its static App Shell, includes cached product details in per-link prefetches without invoking the server, and returns complete static output for buying guides. Personalized cart data still renders when it is needed.
## Next steps
- [Optimize prefetching](/docs/app/guides/optimizing-prefetching#defer-work-to-a-later-stage) to control when individual subtrees render.
- [Ensure instant navigations](/docs/app/guides/instant-navigation) to validate that client navigations into the store show UI immediately.
- [Migrate to Cache Components](/docs/app/guides/migrating-to-cache-components) to replace route-level configs such as `dynamic = 'force-static'` in an existing app.
......@@ -8,12 +8,9 @@ related:
links:
- app/guides/optimizing-the-static-shell
- app/guides/instant-navigation
- app/getting-started/caching
- app/guides/preserving-ui-state
- app/guides/incremental-static-regeneration-cache-components
- app/guides/authentication-with-cache-components
- app/api-reference/functions/generate-static-params
- app/api-reference/config/next-config-js/cacheComponents
- app/getting-started/caching
---
When [Cache Components](/docs/app/api-reference/config/next-config-js/cacheComponents) is enabled, route segment configs like `dynamic`, `revalidate`, and `fetchCache` are replaced by [`use cache`](/docs/app/api-reference/directives/use-cache) and [`cacheLife`](/docs/app/api-reference/functions/cacheLife).
......@@ -176,9 +173,9 @@ export default function Page() {
## `dynamic = "force-static"`
**Remove the config and keep the route fully prerendered.** Without Cache Components, `dynamic = 'force-static'` forced the route to prerender, cached its data, and made `cookies()`, `headers()`, and `useSearchParams()` return empty values.
**Remove the config, then make its caching explicit.** Without Cache Components, `dynamic = 'force-static'` forced the route to prerender, cached its data, and made `cookies()`, `headers()`, and `useSearchParams()` return empty values.
Cache uncached data with [`use cache`](/docs/app/api-reference/directives/use-cache) and a suitable [`cacheLife`](/docs/app/api-reference/functions/cacheLife). After removing the config, Request-time APIs read actual request values. Remove those dependencies if the route must remain fully prerendered.
Cache data that should be reused with [`use cache`](/docs/app/api-reference/directives/use-cache) and a suitable [`cacheLife`](/docs/app/api-reference/functions/cacheLife). After removing the config, Request-time APIs read actual request values. Remove those dependencies if the route must remain fully prerendered.
```tsx filename="app/page.tsx" switcher
// Before
......@@ -224,12 +221,44 @@ export default async function Page() {
}
```
### Enforce static output
> **Good to know**: `ensureStatic` is available in Next.js 16.4 and later. This step is optional. Add it only if the route still has a static output requirement after the migration.
To require a completely static route, add [`ensureStatic = 'navigation'`](/docs/app/api-reference/file-conventions/route-segment-config/ensureStatic#navigation) after migrating its caching:
```tsx filename="app/page.tsx" switcher
export const ensureStatic = 'navigation'
```
```jsx filename="app/page.js" switcher
export const ensureStatic = 'navigation'
```
Unlike `dynamic = 'force-static'`, `ensureStatic` does not make Request-time APIs return empty values. It reports an error if request-specific server work prevents the route from being prerendered. If only the App Shell or per-link prefetch must stay static, choose a less restrictive level. See [Keeping pages static](/docs/app/guides/keeping-pages-static).
## `dynamic = "error"`
**Remove the config.** Without Cache Components, `dynamic = 'error'` required the route to prerender and treated `fetch` requests as cached by default. It raised an error only when uncached data or a Request-time API prevented prerendering.
After removing the config, `fetch` no longer inherits that cached default. To preserve the route's existing caching behavior, wrap those requests in [`use cache`](/docs/app/api-reference/directives/use-cache) and set their lifetime with [`cacheLife`](/docs/app/api-reference/functions/cacheLife). If the route did not rely on the default, no replacement is needed.
### Enforce static validation
> **Good to know**: `ensureStatic` is available in Next.js 16.4 and later. This step is optional. Add it only if the route still has a static output requirement after the migration.
To require a completely static route, add [`ensureStatic = 'navigation'`](/docs/app/api-reference/file-conventions/route-segment-config/ensureStatic#navigation) after making the route's caching explicit:
```tsx filename="app/page.tsx" switcher
export const ensureStatic = 'navigation'
```
```jsx filename="app/page.js" switcher
export const ensureStatic = 'navigation'
```
Use a less restrictive level when only the App Shell or per-link prefetch must stay static. See [Keeping pages static](/docs/app/guides/keeping-pages-static) for how to choose a level.
## `revalidate`
**Replace revalidation times greater than zero with `cacheLife`.** Without Cache Components, `revalidate` set the default revalidation time for an entire route. With Cache Components, place [`use cache`](/docs/app/api-reference/directives/use-cache) around the data or UI that should be cached, then set its lifetime with [`cacheLife`](/docs/app/api-reference/functions/cacheLife).
......
---
title: Optimizing prefetching
description: Resolve per-link URL data with the prefetch prop, include session data in the App Shell, or exclude expensive content from a prefetch.
description: Resolve per-link URL data, include session data in the App Shell, or defer expensive work to a later navigation stage.
nav_title: Optimizing prefetching
related:
title: Learn more
description: Validate your structure and review the caching primitives.
description: Learn more about the APIs and concepts used in this guide.
links:
- app/guides/keeping-pages-static
- app/api-reference/config/next-config-js/partialPrefetching
- app/api-reference/functions/prefetch
- app/api-reference/functions/navigation
- app/api-reference/file-conventions/route-segment-config/prefetch
- app/api-reference/file-conventions/route-segment-config/instant
- app/api-reference/directives/use-cache-private
- app/getting-started/caching
- app/guides/instant-navigation
- app/guides/prefetching
---
Prefetching downloads a route's JavaScript, CSS, and RSC payload before the user navigates to it, so the router can render the next route without waiting for a round trip. The [Prefetching guide](/docs/app/guides/prefetching) covers what the App Router prefetches by default.
With [Cache Components](/docs/app/getting-started/caching) and [Partial Prefetching](/docs/app/api-reference/config/next-config-js/partialPrefetching), a [`<Link>`](/docs/app/api-reference/components/link) prefetches one reusable [**App Shell**](/docs/app/glossary#app-shell) per route by default. The App Shell includes the route's static output. For routes that read [`cookies()`](/docs/app/api-reference/functions/cookies) or [`headers()`](/docs/app/api-reference/functions/headers), it also includes session-specific UI. Links to the same route reuse that App Shell.
With [Cache Components](/docs/app/getting-started/caching) and [Partial Prefetching](/docs/app/api-reference/config/next-config-js/partialPrefetching), Next.js loads server-rendered output in stages, before and during a client navigation. These are the route's [navigation stages](/docs/app/glossary#navigation-stages):
The shared App Shell does not include URL data that varies by destination, such as [`searchParams`](/docs/app/api-reference/file-conventions/page#searchparams-optional) and [`params`](/docs/app/api-reference/file-conventions/page#params-optional). Set `prefetch={true}` on a link to resolve cached content that depends on its [URL data](/docs/app/glossary#url-data) before navigation instead of streaming that content after navigation.
1. A default [`<Link>`](/docs/app/api-reference/components/link) loads the route's [**App Shell**](/docs/app/glossary#app-shell). It holds the route's static output and, for routes that read [`cookies()`](/docs/app/api-reference/functions/cookies) or [`headers()`](/docs/app/api-reference/functions/headers), its session-specific UI. Links to the same route share it.
2. A [`<Link prefetch={true}>`](/docs/app/api-reference/components/link#prefetch) also loads static or cached content that depends on the link's [URL data](/docs/app/glossary#url-data), such as [`searchParams`](/docs/app/api-reference/file-conventions/page#searchparams-optional) and [`params`](/docs/app/api-reference/file-conventions/page#params-optional), which the shared shell cannot include.
3. When the user follows the link, the navigation renders the rest of the route.
Use [`prefetch()`](/docs/app/api-reference/functions/prefetch) and [`navigation()`](/docs/app/api-reference/functions/navigation) to move expensive work to a later stage. To require that a stage stays static across a route, see [Keeping pages static](/docs/app/guides/keeping-pages-static).
## Use the optimizer skill (recommended)
......@@ -39,7 +38,7 @@ Then give the agent the source, destination, and UI that should be available imm
Make the search results instant when navigating from / to /search?q=react. Use the next-partial-prefetching-optimizer Skill.
```
This guide assumes [Cache Components](/docs/app/getting-started/caching) with [`partialPrefetching`](/docs/app/api-reference/config/next-config-js/partialPrefetching) enabled:
Enable [Cache Components](/docs/app/getting-started/caching) and [`partialPrefetching`](/docs/app/api-reference/config/next-config-js/partialPrefetching) before applying these optimizations:
```ts filename="next.config.ts" highlight={4,5}
import type { NextConfig } from 'next'
......@@ -52,7 +51,7 @@ const nextConfig: NextConfig = {
export default nextConfig
```
It also assumes your route is already structured for instant navigation. If it isn't, start with the [Instant navigation guide](/docs/app/guides/instant-navigation) to validate its caching structure first.
If the route is not yet structured for instant navigation, start with the [Instant navigation guide](/docs/app/guides/instant-navigation) to validate its caching structure.
## Resolve URL data at prefetch time
......@@ -118,11 +117,11 @@ async function search(q: string) {
Without `prefetch={true}`, the App Shell renders `<h1>` and shows the `<Results>` fallback. The query resolves after the click and streams the results in.
With `prefetch={true}` on the link, the router prefetches a prerender that resolves `<Results>` before the click. The `q` value comes from the link's URL, known at prefetch time, and the cached `search(q)` provides the result. On the click, the results render immediately, with no fallback.
With `prefetch={true}` on the link, the router requests a per-link prefetch that resolves `<Results>` before the click. The `q` value comes from the link's URL, which is known at prefetch time, and the cached `search(q)` call provides the result. When the user clicks, the results render immediately without showing the fallback.
The prerender advances through anything static or cached, then stops at uncached reads and falls back to the surrounding `<Suspense>` boundary. That boundary is already in place from [structuring the route for instant navigation](/docs/app/guides/instant-navigation).
Next.js includes static and cached content in the prefetch until it reaches an uncached read. It then includes the fallback from the surrounding `<Suspense>` boundary. That boundary is already in place from [structuring the route for instant navigation](/docs/app/guides/instant-navigation).
Generating the per-link prefetch costs **a server invocation per prefetchable link**, so it is opt-in per link. On pages where all the content is statically renderable, Next.js serves the prefetch from the static cache instead. A page that accesses non-static data is generated per prefetch.
Generating the per-link prefetch costs **a server invocation per prefetchable link**, so it is opt-in per link. On pages where all the content is statically renderable, Next.js serves the prefetch from the static cache instead. A page that accesses non-static data is generated per prefetch, unless that access is [deferred to the navigation](#keep-the-prefetch-static).
> **Good to know:** A cold cache (first visit, or after expiration) means the server still has to compute the cached result. Users may see a loading spinner on that first navigation. Subsequent navigations are instant as long as the cache is warm.
......@@ -151,7 +150,7 @@ export default function DashboardLayout({
}
```
The cookie itself is session data the App Shell already knows. But `"use cache"` can't read `cookies()` inside the cached function, so two patterns bridge it:
The App Shell render can read session data. However, `"use cache"` cannot call `cookies()` inside the cached function, so use one of these patterns:
- **Extract and pass** when the lookup result is shared across many sessions.
- **`"use cache: private"`** when it is tied to one.
......@@ -206,23 +205,42 @@ async function getUser() {
}
```
Here `cookies()` lives inside the cached function, which only works under `"use cache: private"`. This is also the pattern when you can't extract the runtime data from the outside: auth helpers that check `Date.now()` against a token's expiry, or session helpers that read cookies deep inside their own code, can't be wrapped at the call site.
Here `cookies()` lives inside the cached function, which only works under `"use cache: private"`. Use the same pattern when runtime data cannot be extracted at the call site. For example, an authentication helper may compare `Date.now()` with a token's expiration, or a session helper may read cookies within its own code.
Everything inside the scope shares the same lifetime. Colocate `"use cache: private"` as close to the runtime data access as possible.
## Exclude content from a prefetch
## Defer work to a later stage
The App Shell is shared by the links into a route. A per-link prefetch runs for a visible `<Link prefetch={true}>`, and the navigation runs when the user clicks. Expensive work may not be worth generating for links the user never follows.
Uncached work is already left out of prefetches. For cacheable work, `next/cache` exports functions that defer the code below each call:
- [`prefetch()`](/docs/app/api-reference/functions/prefetch) defers the code until a per-link prefetch or navigation.
- [`navigation()`](/docs/app/api-reference/functions/navigation) defers the code until navigation.
Optimizing a prefetch also means excluding content from it. Some subtrees are expensive enough to produce that you would rather not pay for them on every prefetch of the route.
In the following diagram, a gray dashed outline marks the Suspense fallback, while blue marks the deferred work once it renders:
Awaiting [`navigation()`](/docs/app/api-reference/functions/navigation) above the work leaves it out of every prefetch, so it is produced on the navigation. The nearest [`<Suspense>`](https://react.dev/reference/react/Suspense) fallback is what the user sees while it streams in. Take the dashboard again, where a ranking keyed on the session is too expensive to produce for every link into the route:
<Image
alt="The Shell, Prefetch, and Navigation stages, with bars showing that work below prefetch() renders from the per-link prefetch onward and work below navigation() renders only during navigation, while earlier stages show the Suspense fallback"
srcLight="/docs/light/navigation-stage-visual.png"
srcDark="/docs/dark/navigation-stage-visual.png"
width="1200"
height="480"
/>
Both functions apply only during runtime rendering, so they do not change a fully static route. Each call defers the component that awaits it and that component's descendants. Earlier stages render the nearest [`<Suspense>`](https://react.dev/reference/react/Suspense) fallback, which the deferred subtree replaces when its stage runs. Unlike [`connection()`](/docs/app/api-reference/functions/connection), neither function makes the subtree request-dependent, so functions within it can still use `use cache`. See [How `navigation()` differs from `connection()`](/docs/app/api-reference/functions/navigation#how-navigation-differs-from-connection).
### Keep expensive session data out of the App Shell
Take the dashboard again. A ranking keyed on the session is expensive, and every default `<Link>` into the dashboard would generate it for the shell. Await `prefetch()` above the ranking so that only a `<Link prefetch={true}>` resolves it before the click:
```tsx filename="app/dashboard/recommendations.tsx" highlight={6}
import { cookies } from 'next/headers'
import { navigation } from 'next/cache'
import { prefetch } from 'next/cache'
async function Recommendations() {
const session = (await cookies()).get('session')?.value
await navigation()
await prefetch()
const items = await rank(session)
return <List items={items} />
}
......@@ -233,13 +251,102 @@ async function rank(session?: string) {
}
```
The session is read above `navigation()`, so it resolves in the shell like any other session data. Only the ranking is left out, and it keeps its cache lifetime.
The session is read above `prefetch()`, so it still resolves in the shell. The App Shell does not generate the ranking. A default `<Link>` includes the `<Suspense>` fallback, which the ranking replaces during navigation. A `<Link prefetch={true}>` resolves the ranking before the click. `rank` keeps its cache lifetime in both cases.
Neither function can be awaited inside a cached scope, so the directive goes on a function called below it, as `rank` does here.
### Wait for the navigation
Consider an inbox where each visible thread uses `<Link prefetch={true}>`. The prefetch should include the thread subject, but fetching every message body before the user opens it would waste work.
Render the latest message in its own `<Suspense>` boundary and await `navigation()` before loading it:
```tsx filename="app/inbox/[threadId]/thread.tsx" highlight={19}
import { Suspense } from 'react'
import { navigation } from 'next/cache'
import { getLatestMessage, getThreadSummary } from '@/lib/mail'
export async function Thread({ threadId }: { threadId: string }) {
const thread = await getThreadSummary(threadId)
return (
<article>
<h1>{thread.subject}</h1>
<Suspense fallback={<p>Loading message...</p>}>
<LatestMessage threadId={threadId} />
</Suspense>
</article>
)
}
async function LatestMessage({ threadId }: { threadId: string }) {
await navigation()
const message = await getLatestMessage(threadId)
return <p>{message.body}</p>
}
```
Both queries remain cached:
```ts filename="lib/mail.ts"
import { db } from '@/lib/db'
export async function getThreadSummary(threadId: string) {
'use cache'
return db.thread.findUniqueOrThrow({
select: { subject: true },
where: { id: threadId },
})
}
export async function getLatestMessage(threadId: string) {
'use cache'
return db.message.findFirstOrThrow({
orderBy: { sentAt: 'desc' },
select: { body: true },
where: { threadId },
})
}
```
The per-link prefetch includes the cached subject and the message fallback. The cached message body loads when the user opens the thread, then remains available for later visits.
{/* TODO: once `<Link prefetch="navigation">` ships, document it here as the opt-in for a link that also prefetches cacheable work deferred with `navigation()`. */}
Leaving the subtree uncached would also keep it out of prefetches, but it would lose its cache lifetime on navigation too. For `use cache` content, a [`stale`](/docs/app/api-reference/functions/cacheLife#stale) time of five minutes or more lets the client-side router reuse it after the first navigation. Below that, each navigation fetches it again.
### Keep the prefetch static
Without it, keeping a subtree out of a prefetch means leaving it uncached, which gives up that lifetime on the navigation too. Awaiting `navigation()` inside a cached scope is not allowed, so put the caching directive on a function called below it, as `rank` does here.
When every read of `cookies()`, `headers()`, `params`, and `searchParams` sits below `navigation()`, a runtime prefetch would produce the same output as the build. Next.js can therefore serve the prefetch from static output. A CDN can cache that output, so a link into the route requires no server compute.
For a subtree that would otherwise sit in the App Shell, but that a `<Link prefetch={true}>` should still resolve before the click, use [`prefetch()`](/docs/app/api-reference/functions/prefetch) instead.
The dashboard cannot take this shape, because `<UserNav>` reads the team cookie in the shell. A feed with a static header can:
Unlike [`connection()`](/docs/app/api-reference/functions/connection), `navigation()` does not make the subtree request-dependent. This lets reusable content keep its cache lifetime while waiting for navigation. See [How `navigation()` differs from `connection()`](/docs/app/api-reference/functions/navigation#how-navigation-differs-from-connection) for the full comparison.
```tsx filename="app/feed/page.tsx" highlight={17}
import { Suspense } from 'react'
import { cookies } from 'next/headers'
import { navigation } from 'next/cache'
export default function Page() {
return (
<>
<FeedHeader /> {/* static, and so is the whole prefetch */}
<Suspense fallback={<p>Loading stories...</p>}>
<Stories />
</Suspense>
</>
)
}
async function Stories() {
await navigation()
const topic = (await cookies()).get('topic')?.value ?? 'all'
return <StoryList items={await getStories(topic)} />
}
```
Reading the cookie below `navigation()` does not make the per-link prefetch render per request, because that read would not have resolved during the prefetch anyway. The same holds for `prefetch()` and the App Shell. When every `cookies()` and `headers()` read sits below `prefetch()`, the shell is served from static output. Reading `params` or `searchParams` does not require a runtime shell. URL data is excluded from the shared shell, but it can make a per-link prefetch render at runtime unless it sits below `navigation()`.
Each call defers one subtree. To require static output for the whole route, so a later change cannot reintroduce request-time rendering, set [`ensureStatic`](/docs/app/api-reference/file-conventions/route-segment-config/ensureStatic). The [Keeping pages static](/docs/app/guides/keeping-pages-static) guide walks through each level.
## Test prefetched and deferred content
......@@ -273,6 +380,8 @@ test('prefetches the product summary but not reviews', async ({ page }) => {
While the `instant()` callback is running, dynamic content is paused. In this example, the product summary is part of the prefetched UI, while reviews wait for navigation. The final assertion confirms that the reviews render after the pause is released.
In development, a `prefetch()` or `navigation()` call outside `<Suspense>` surfaces an [Instant Insight](/docs/messages/instant-navigation-stage). A fully prerendered route is unaffected, but the insight identifies that the call would defer content without a fallback if the route later requires runtime rendering. Calls in [`generateMetadata()`](/docs/messages/instant-navigation-stage-metadata) and [`generateViewport()`](/docs/messages/instant-navigation-stage-viewport) have separate insights.
## Trade-offs
Use `prefetch={true}` on routes where:
......@@ -291,22 +400,20 @@ Skip it when the prefetch can't produce a better UI than the App Shell. Each vis
A per-link prefetch is best-effort. It only helps the navigations where it completes before the click. On a slow connection, on a feed of many links, or on a direct visit, it may not be ready when the user navigates, and the navigation falls back to the App Shell.
When many links to a route are visible at once, such as a grid of cards, each `<Link prefetch={true}>` prefetches that link's content as it enters the viewport, so the grid makes one such server request per card. Prefetch on intent instead. A [hover-triggered prefetch](/docs/app/guides/prefetching#hover-triggered-prefetch) fetches only the links the user is likely to click. The default `<Link>` (without `prefetch={true}`) prefetches only the App Shell, so it doesn't carry this cost.
When many links to a route are visible at once, such as a grid of cards, each `<Link prefetch={true}>` prefetches that link's content as it enters the viewport, so the grid makes one such server request per card. Prefetch on intent instead. A [hover-triggered prefetch](/docs/app/guides/prefetching#hover-triggered-prefetch) fetches only the links the user is likely to click. The default `<Link>` (without `prefetch={true}`) loads only the App Shell, so it doesn't carry this cost.
| | App Shell | Per-link prefetch with `prefetch={true}` |
| ------- | ------------------------------------------- | ---------------------------------------- |
| Scope | One per route | One per visible `<Link prefetch={true}>` |
| Content | Route's rendered output minus per-link data | Same, plus per-link URL data resolved |
| Cost | Bounded by route count | Bounded by visible-link count |
| Role | Default prefetch | More rendered before click |
| | App Shell | Per-link prefetch with `prefetch={true}` | Navigation |
| ------- | ----------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ---------------------------------------------------- |
| Scope | One per route | One per visible `<Link prefetch={true}>` | One per click |
| Content | Route's rendered output minus per-link data and work below `prefetch()` or `navigation()` | App Shell plus per-link URL data and work below `prefetch()`, excluding work below `navigation()` | Everything left, including work below `navigation()` |
| Cost | Bounded by route count | Bounded by visible-link count | Bounded by navigations |
| Role | Default prefetch | More rendered before click | Completes the route |
[Excluding content](#exclude-content-from-a-prefetch) is one more control on top of these. The trade is generating content for a prefetch that may never be used, against momentarily showing a `<Suspense>` fallback while that content streams in.
[Deferring work](#defer-work-to-a-later-stage) avoids generating content for prefetches that may never be used. The tradeoff is that a navigation may show the nearest `<Suspense>` fallback while the deferred content renders.
## Next steps
- [Adopting Partial Prefetching](/docs/app/guides/adopting-partial-prefetching) for how `<Link>` behaves under the new model and how to migrate existing apps.
- [`prefetch` API reference](/docs/app/api-reference/file-conventions/route-segment-config/prefetch) for all prefetch modes.
- [`use cache: private` reference](/docs/app/api-reference/directives/use-cache-private) for per-user caching specifics.
- [`prefetch()`](/docs/app/api-reference/functions/prefetch) and [`navigation()`](/docs/app/api-reference/functions/navigation) for the full behavior of each prefetch stage.
- [`prefetch()`](/docs/app/api-reference/functions/prefetch) and [`navigation()`](/docs/app/api-reference/functions/navigation) for the full behavior of each navigation stage API.
- [Keeping pages static](/docs/app/guides/keeping-pages-static) for requiring a static App Shell, prefetch, or complete route with `ensureStatic`.
- [Instant navigation guide](/docs/app/guides/instant-navigation) for validating the route's caching structure.
- [Caching](/docs/app/getting-started/caching) for background on `use cache`, Suspense, and Partial Prerendering.
......@@ -4,6 +4,7 @@ description: Learn how to build public, "static" pages that share data across us
nav_title: Public pages
related:
links:
- app/guides/keeping-pages-static
- app/guides/incremental-static-regeneration-cache-components
---
......@@ -249,10 +250,9 @@ If we refresh the page one last time, we can see most of the page loads instantl
We've learned how to build mostly static pages that include pockets of dynamic content.
We started with a static page, added async work, and resolved the blocking behavior by caching what could be prerendered, and streaming what couldn't.
We started with a static page, added async work, and resolved the blocking behavior by caching what could be prerendered and streaming what could not. From here, you can:
In future guides, we'll learn how to:
- Revalidate prerendered pages or cached data.
- Create variants of the same page with route params.
- Create private pages with personalized user data.
- [Keep selected route output static](/docs/app/guides/keeping-pages-static) as the application changes.
- [Revalidate prerendered pages or cached data](/docs/app/guides/incremental-static-regeneration-cache-components).
- [Create variants with route parameters](/docs/app/api-reference/functions/generate-static-params).
- [Add authentication to a Cache Components application](/docs/app/guides/authentication-with-cache-components).
---
title: ensureStatic
description: API reference for the ensureStatic route segment config, which requires selected route output to be static instead of rendered per request.
description: Require selected route output to remain static instead of rendering per request with the ensureStatic route segment config.
related:
title: Next Steps
description: Learn how to control which route output must be static.
description: Choose a static level or defer selected subtrees to a later navigation stage.
links:
- app/guides/keeping-pages-static
- app/guides/optimizing-prefetching
- app/api-reference/functions/prefetch
- app/api-reference/functions/navigation
- app/api-reference/file-conventions/route-segment-config/instant
- app/api-reference/config/next-config-js/partialPrefetching
---
The `ensureStatic` route segment config requires selected route output to be static instead of rendered per request. Export it from a [page](/docs/app/api-reference/file-conventions/page) or [layout](/docs/app/api-reference/file-conventions/layout) to enforce this requirement for the [App Shell](/docs/app/glossary#app-shell), per-link prefetches, or the complete server-rendered route.
Use it so later changes cannot add request-time server rendering to a navigation stage that must stay static. See [Keeping pages static](/docs/app/guides/keeping-pages-static) for a worked example of each level.
> **Good to know**:
>
> - The `ensureStatic` export only works when [`cacheComponents`](/docs/app/api-reference/config/next-config-js/cacheComponents) is enabled. The build fails otherwise.
......@@ -39,7 +40,7 @@ export default function Layout({ children }) {
The export accepts `'auto'`, `'shell'`, `'prefetch'`, `'navigation'`, or `false`. The default is `'auto'`, which is equivalent to omitting the export.
`ensureStatic` controls which server-rendered output must be static. With Partial Prefetching, that output can be the App Shell, an optional per-link prefetch, or the complete route rendered during navigation. These outputs are called [navigation stages](/docs/app/glossary#navigation-stages). Each level includes the requirements above it.
`ensureStatic` controls which server-rendered output must be static. With Partial Prefetching, that output can be the App Shell, an optional per-link prefetch, or the complete route rendered during navigation. These outputs are called [navigation stages](/docs/app/glossary#navigation-stages). Each stricter level also includes the earlier stages.
| Value | Output that must be static |
| ------------------ | -------------------------------- |
......@@ -52,23 +53,23 @@ The export accepts `'auto'`, `'shell'`, `'prefetch'`, `'navigation'`, or `false`
### `'shell'`
Requires the [App Shell](/docs/app/glossary#app-shell) loaded by a default `<Link>` to be static. This only works with [Partial Prefetching](/docs/app/api-reference/config/next-config-js/partialPrefetching).
Requires the [App Shell](/docs/app/glossary#app-shell) loaded by a default `<Link>` to be static. Without [Partial Prefetching](/docs/app/api-reference/config/next-config-js/partialPrefetching) there is no App Shell, so the value has no effect and Next.js logs a warning.
The shell can include static or cached content and `<Suspense>` fallbacks. Request-specific content behind `<Suspense>` can render during a later per-link prefetch with [`<Link prefetch={true}>`](/docs/app/api-reference/components/link#prefetch), or during navigation.
For an individual subtree, [`await prefetch()`](/docs/app/api-reference/functions/prefetch) provides similar behavior by deferring code below the call to a per-link prefetch or navigation. Setting `'shell'` enforces that stage boundary across the route without adding `await prefetch()` to each request-specific subtree.
For an individual subtree, [`await prefetch()`](/docs/app/api-reference/functions/prefetch) provides similar behavior by deferring code below the call to a per-link prefetch or navigation. Setting `'shell'` enforces that stage boundary across the route without adding `await prefetch()` to each request-specific subtree. See [Defer work to a later stage](/docs/app/guides/optimizing-prefetching#defer-work-to-a-later-stage) for the per-subtree controls.
> **Good to know**: `'shell'` only covers the App Shell. If the route reads `cookies()`, `headers()`, or URL data anywhere that is not below [`await navigation()`](/docs/app/api-reference/functions/navigation), each visible [`<Link prefetch={true}>`](/docs/app/api-reference/components/link#prefetch) into it still renders its prefetch on the server, and the prefetched UI gives no sign of that work. Use [`'prefetch'`](#prefetch) when per-link prefetches must also come from static output.
> **Good to know**: `'shell'` does not require per-link prefetches to be static. If the route reads `cookies()`, `headers()`, or URL data before [`await navigation()`](/docs/app/api-reference/functions/navigation), each visible [`<Link prefetch={true}>`](/docs/app/api-reference/components/link#prefetch) can still trigger a server render. Use [`'prefetch'`](#prefetch) when per-link prefetches must also come from static output.
### `'prefetch'`
Requires both the App Shell and per-link prefetches to be static. This only works with [Partial Prefetching](/docs/app/api-reference/config/next-config-js/partialPrefetching).
Requires both the App Shell and per-link prefetches to be static. Without [Partial Prefetching](/docs/app/api-reference/config/next-config-js/partialPrefetching), the value adds no requirement and links keep their normal full-prefetch behavior. A full prefetch can include request-specific data and is not guaranteed to be static.
A per-link prefetch from [`<Link prefetch={true}>`](/docs/app/api-reference/components/link#prefetch) can load static or cached [URL-specific content](/docs/app/guides/optimizing-prefetching#resolve-url-data-at-prefetch-time) before the user follows the link. Request-specific content behind `<Suspense>` renders when the navigation completes the route.
The [static HTML shell](/docs/app/glossary#static-shell) can also include this static or cached per-link content. Unlike a per-link prefetch, it cannot include request-specific data because the HTML shell is prerendered.
For an individual subtree, [`await navigation()`](/docs/app/api-reference/functions/navigation) provides similar behavior by deferring code below the call until navigation. Setting `'prefetch'` enforces that stage boundary across the route without adding `await navigation()` to each request-specific subtree.
For an individual subtree, [`await navigation()`](/docs/app/api-reference/functions/navigation) provides similar behavior by deferring code below the call until navigation. Setting `'prefetch'` enforces that stage boundary across the route without adding `await navigation()` to each request-specific subtree. See [Keep the prefetch static](/docs/app/guides/optimizing-prefetching#keep-the-prefetch-static) for shaping one route this way.
### `'navigation'`
......@@ -78,11 +79,11 @@ To require static server output for the entire app, set `'navigation'` on the ro
#### Validation
`'shell'` and `'prefetch'` allow request-specific work to be deferred to a later navigation stage. `'navigation'` is the final server-rendering stage, so no later stage remains. Next.js therefore validates that all server output is static.
With `'shell'` and `'prefetch'`, request-specific work inside `<Suspense>` can move to a later navigation stage. These values do not add build validation. When [Instant Navigation validation](/docs/messages/instant-navigation-validation) is enabled, it can report request-specific work outside `<Suspense>` because it blocks the navigation.
Next.js validates this requirement during both `next dev` and `next build`. In development, errors include source-mapped stack traces that update as you edit. Build output is more abbreviated, so you may need to run [`next build --debug-prerender`](/docs/app/guides/building#debug-prerender-errors) for detailed stack traces and code frames. See [Ensuring instant navigations](/docs/app/guides/instant-navigation) for the development workflow.
`'navigation'` is the final server-rendering stage, so no later stage remains. Next.js validates its complete static-output requirement during both `next dev` and `next build`. In development, errors include source-mapped stack traces that update as you edit. Build output is more abbreviated, so you may need to run [`next build --debug-prerender`](/docs/app/guides/building#debug-prerender-errors) for detailed stack traces and code frames. See [Ensuring instant navigations](/docs/app/guides/instant-navigation) for the development workflow.
The following server content fails validation, even when it is wrapped in `<Suspense>` or the segment sets [`instant = false`](/docs/app/api-reference/file-conventions/route-segment-config/instant#disabling-instant):
With `ensureStatic = 'navigation'`, the following server content fails validation, even when it is wrapped in `<Suspense>` or the segment sets [`instant = false`](/docs/app/api-reference/file-conventions/route-segment-config/instant#disabling-instant):
- [Uncached data](/docs/messages/static-route-dynamic), including a `fetch` or database call without [`use cache`](/docs/app/api-reference/directives/use-cache), and [`connection()`](/docs/app/api-reference/functions/connection).
- [Runtime data](/docs/messages/static-route-runtime), such as `cookies()`, `headers()`, and server-side `searchParams`.
......@@ -91,7 +92,7 @@ The following server content fails validation, even when it is wrapped in `<Susp
These constraints also apply to [`generateMetadata`](/docs/app/api-reference/functions/generate-metadata) and [`generateViewport`](/docs/app/api-reference/functions/generate-viewport).
Data cached with `use cache` can be prerendered. [`prefetch()`](/docs/app/api-reference/functions/prefetch) and [`navigation()`](/docs/app/api-reference/functions/navigation) are also allowed because their work completes during the static prerender.
Data cached with `use cache` can be prerendered. [`prefetch()`](/docs/app/api-reference/functions/prefetch) and [`navigation()`](/docs/app/api-reference/functions/navigation) are also allowed because a static prerender continues through their stage boundaries.
#### Dynamic route parameters
......@@ -119,7 +120,7 @@ With Partial Prefetching, `false` keeps the route's normal rendering behavior an
[`instant`](/docs/app/api-reference/file-conventions/route-segment-config/instant) validates whether a navigation can update the UI immediately. Cached or prerendered UI can satisfy this requirement while request-specific content streams later behind `<Suspense>`.
Setting `instant = false` disables instant-navigation validation. It does not relax an `ensureStatic` requirement.
Setting `instant = false` disables Instant Navigation validation for the route. The `'shell'` and `'prefetch'` values still make the client request the corresponding static output, but neither value adds separate build validation. A static prefetch can still include a parent layout, metadata, and Client Component preload hints even when the page UI renders only after the user follows the link. The `'navigation'` value uses separate complete static-output validation, which `instant = false` does not relax.
## Combining levels across layouts and pages
......
---
title: instant
description: API reference for the instant route segment config.
description: Configure instant navigation validation for a route segment.
related:
title: Next Steps
description: Learn how to use instant navigations in practice.
links:
- app/guides/instant-navigation
- app/api-reference/file-conventions/route-segment-config/ensureStatic
- app/getting-started/caching
- app/getting-started/revalidating
- app/api-reference/directives/use-cache
......@@ -93,6 +94,10 @@ Setting `false` on the root layout disables static shell validation for the enti
Each error identifies the component that would block navigation. The fix is usually to cache the data with `use cache` or wrap it in a `<Suspense>` boundary.
## How `instant` differs from `ensureStatic`
`instant` validates whether a navigation shows UI immediately. [`ensureStatic`](/docs/app/api-reference/file-conventions/route-segment-config/ensureStatic) requires selected server-rendered output to be static instead of rendered for each request. A route can be fully static and still block a navigation, for example when a Client Component loads data in the browser.
## Configuring validation defaults
By default (`validationLevel: 'warning'`), Cache Components apps validate every Page and Default segment in development. The `experimental.instantInsights.validationLevel` config tunes this behavior — for example, to limit validation to segments that opt in explicitly via `instant`.
......
---
title: prefetch
description: API reference for the prefetch route segment config.
nav_title: prefetch config
description: Configure how a route segment is prefetched during client navigation.
related:
title: Next Steps
description: Learn how to use instant navigations in practice.
......
---
title: navigation
description: API Reference for the navigation function, which keeps a subtree out of a route's prefetches so it renders when the user navigates.
nav_title: navigation()
description: Defer runtime work until the user navigates with the navigation function.
related:
links:
- app/guides/optimizing-prefetching
- app/guides/keeping-pages-static
- app/api-reference/functions/prefetch
- app/api-reference/functions/connection
- app/guides/adopting-partial-prefetching
- app/api-reference/functions/io
- app/api-reference/config/next-config-js/partialPrefetching
- app/api-reference/config/next-config-js/cacheComponents
---
Calling `await navigation()` defers the code below it to the navigation, instead of rendering it when a link to the route is prefetched. The fallback of the nearest [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary takes its place in the prefetch, and the deferred content renders when the user navigates.
Calling `await navigation()` keeps runtime work below it out of the [App Shell](/docs/app/glossary#app-shell) and per-link prefetches. The work runs when the user navigates, while the fallback of the nearest [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary renders in the prefetched output.
It is meant to defer content that a prefetch would otherwise render, even content that would sit in the App Shell, typically because it depends on session data or URL data and is expensive to generate. During a build-time prerender nothing is deferred, so content below `navigation()` is prerendered as usual.
Use `navigation()` for reusable content that is expensive to generate and should wait until navigation. Static prerenders still include the content in their output, so it can appear in a static prefetch.
## Usage
......@@ -30,19 +30,21 @@ const nextConfig: NextConfig = {
export default nextConfig
```
A route is then rendered in three stages, and content can arrive at any of them:
With Partial Prefetching enabled, Next.js loads server-rendered output in stages, before and during a client navigation. These are the route's [navigation stages](/docs/app/glossary#navigation-stages):
1. The [App Shell](/docs/app/glossary#app-shell), which every `<Link>` into the route prefetches, and which holds the part of the route that does not depend on the URL.
2. A per-link prefetch, requested with [`<Link prefetch={true}>`](/docs/app/api-reference/components/link#prefetch), which resolves the URL and adds the content that depends on it.
3. The navigation itself, which covers everything left.
1. A default `<Link>` loads the [App Shell](/docs/app/glossary#app-shell), which holds the part of the route that does not depend on the URL.
2. An optional [`<Link prefetch={true}>`](/docs/app/api-reference/components/link#prefetch) can also load content that depends on the link's URL.
3. When the user follows the link, the navigation renders the rest of the route.
Awaiting `navigation()` keeps content out of the App Shell and out of per-link prefetches, so it renders only on the navigation.
During runtime rendering, awaiting `navigation()` keeps content out of the App Shell and per-link prefetches, so it renders during navigation. Static prerenders can still include the content.
Without Partial Prefetching, `navigation()` still defers the content for a default `<Link>`, but [`<Link prefetch={true}>`](/docs/app/api-reference/components/link#prefetch) fetches the whole route, deferred content included, the same as a navigation.
To keep content out of the App Shell while still including it in a per-link prefetch, use [`prefetch()`](/docs/app/api-reference/functions/prefetch).
Everything above `navigation()` renders in the prefetch, and everything below renders on the navigation. Deferral is scoped to the component that awaits it and the tree below: sibling branches render in the prefetch as usual. Place it above the code to defer, and wrap the component in [`<Suspense>`](https://react.dev/reference/react/Suspense):
> **Good to know**: `navigation()` defers one subtree. To require a static App Shell and static per-link prefetches across the route, use [`ensureStatic = 'prefetch'`](/docs/app/api-reference/file-conventions/route-segment-config/ensureStatic#prefetch). See [Keeping pages static](/docs/app/guides/keeping-pages-static) for a worked example.
Everything above `navigation()` can render in the App Shell or a per-link prefetch, while everything below waits for navigation. Deferral is scoped to the component that awaits it and the tree below: sibling branches keep their existing behavior. Place it above the code to defer, and wrap the component in [`<Suspense>`](https://react.dev/reference/react/Suspense):
```tsx filename="app/post/[slug]/page.tsx" highlight={20} switcher
import { Suspense } from 'react'
......@@ -64,7 +66,7 @@ export default function Page({ params }: PageProps<'/post/[slug]'>) {
}
async function Comments({ params }: { params: Promise<{ slug: string }> }) {
await navigation() // everything below renders on the navigation
await navigation() // runtime work below renders on navigation
const { slug } = await params
const sort = (await cookies()).get('comment-sort')?.value ?? 'newest'
const items = await getComments(slug, sort)
......@@ -98,7 +100,7 @@ export default function Page({ params }) {
}
async function Comments({ params }) {
await navigation() // everything below renders on the navigation
await navigation() // runtime work below renders on navigation
const { slug } = await params
const sort = (await cookies()).get('comment-sort')?.value ?? 'newest'
const items = await getComments(slug, sort)
......@@ -122,17 +124,17 @@ Put the directive on a function called below it, as `getComments` does here. Awa
The [`connection()`](/docs/app/api-reference/functions/connection) function waits for a real request. It excludes the code that follows from prerendering and prefetching, making that work request-dependent.
`navigation()` only excludes the code that follows from route prefetches. It resolves when the user navigates without making that work request-dependent. A function called after `await navigation()` can therefore use [`"use cache"`](/docs/app/api-reference/directives/use-cache) and keep its cache lifetime without generating its result during prefetching.
Awaiting `navigation()` excludes the code that follows from route prefetches. It resolves when the user navigates without making that work request-dependent. A function called after `await navigation()` can therefore use [`"use cache"`](/docs/app/api-reference/directives/use-cache) and keep its cache lifetime without generating its result during prefetching.
Use `connection()` when the work must run for a real request. Use `navigation()` when the work is reusable but should wait until the user navigates.
## When to use it
Reach for it when the content below `navigation()` is expensive to produce, in compute, in upstream requests, or in latency, and you do not want every prefetch of the route to generate it.
Use `navigation()` when the content below it is expensive to produce and no prefetch should generate it.
Neither prefetch stage runs that code, so its upstream requests are not issued until the user navigates.
Neither the runtime App Shell nor a runtime per-link prefetch runs that code, so its upstream requests are not issued until the user navigates.
Keeping that content out of a prefetch would otherwise mean leaving it uncached.
Leaving content uncached also keeps it out of prefetches, but gives up its cache lifetime.
With `navigation()` the content can be cached with [`use cache`](/docs/app/api-reference/directives/use-cache), given a lifetime, and deferred to the navigation. Give it a [`stale`](/docs/app/api-reference/functions/cacheLife#stale) time of five minutes or more and the client-side router reuses it after the first time a user navigates into the route. Below that, a [short lifetime keeps it out of the App Shell](/docs/app/api-reference/functions/cacheLife#prerendering-behavior), so each navigation fetches it again.
......@@ -167,7 +169,7 @@ async function Stories() {
- The function has no effect on the initial load of a page.
- Reading `cookies()` or `headers()` below `navigation()` does not make the route's prefetches render per request, so they can still be served from static output. Those accesses are ignored, because they would not have resolved in a prefetch either.
- A call outside a `<Suspense>` boundary surfaces an [Instant Insight](/docs/messages/instant-navigation-stage) in development. It is reported even on a page that is currently prerendered in full, because the same page starts deferring content as soon as it switches to a runtime shell.
- A call outside a `<Suspense>` boundary surfaces an [Instant Insight](/docs/messages/instant-navigation-stage) in development. A fully prerendered route is unaffected, but the insight identifies that the call would defer content without a fallback if the route later requires runtime rendering.
- Calling it inside `use cache`, `use cache: private`, [`unstable_cache()`](/docs/app/api-reference/functions/unstable_cache), [`after()`](/docs/app/api-reference/functions/after), [`generateStaticParams`](/docs/app/api-reference/functions/generate-static-params), or a Client Component throws.
## Reference
......
---
title: prefetch
description: API Reference for the prefetch function, which keeps a subtree out of a route's App Shell so it renders on a per-link prefetch or a navigation.
nav_title: prefetch()
description: Defer runtime work until a per-link prefetch or navigation with the prefetch function.
related:
links:
- app/guides/optimizing-prefetching
- app/guides/keeping-pages-static
- app/api-reference/functions/navigation
- app/api-reference/functions/connection
- app/guides/adopting-partial-prefetching
- app/api-reference/functions/io
- app/api-reference/config/next-config-js/partialPrefetching
- app/api-reference/config/next-config-js/cacheComponents
---
Calling `await prefetch()` defers the code below it to a per-link prefetch or a navigation, instead of rendering it in the route's [App Shell](/docs/app/glossary#app-shell). The fallback of the nearest [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary takes its place in the shell, and the deferred content renders once one of those happens.
Calling `await prefetch()` keeps runtime work below it out of the route's [App Shell](/docs/app/glossary#app-shell). The work can run during a per-link prefetch or navigation, while the fallback of the nearest [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary renders in the shell.
It is meant to defer content that the App Shell would otherwise render, typically content that depends on session data and is expensive to generate. During a build-time prerender nothing is deferred, so content below `prefetch()` is prerendered as usual.
Use `prefetch()` for content that the App Shell would otherwise render but that is expensive to generate. Static prerenders still include the content in their output.
## Usage
......@@ -30,16 +30,18 @@ const nextConfig: NextConfig = {
export default nextConfig
```
A route is then rendered in three stages, and content can arrive at any of them:
With Partial Prefetching enabled, Next.js loads server-rendered output in stages, before and during a client navigation. These are the route's [navigation stages](/docs/app/glossary#navigation-stages):
1. The App Shell, which every `<Link>` into the route prefetches, and which holds the part of the route that does not depend on the URL.
2. A per-link prefetch, requested with [`<Link prefetch={true}>`](/docs/app/api-reference/components/link#prefetch), which resolves the URL and adds the content that depends on it.
3. The navigation itself, which covers everything left.
1. A default `<Link>` loads the App Shell, which holds the part of the route that does not depend on the URL.
2. An optional [`<Link prefetch={true}>`](/docs/app/api-reference/components/link#prefetch) can also load content that depends on the link's URL.
3. When the user follows the link, the navigation renders the rest of the route.
Awaiting `prefetch()` keeps content out of the App Shell, so it renders only on a per-link prefetch or on the navigation.
During runtime rendering, awaiting `prefetch()` keeps content out of the App Shell, so it renders during a per-link prefetch or navigation. Static prerenders can still include the content.
To keep content out of per-link prefetches as well, so it renders only on the navigation, use [`navigation()`](/docs/app/api-reference/functions/navigation).
> **Good to know**: `prefetch()` defers one subtree. To require a static App Shell across the route, use [`ensureStatic = 'shell'`](/docs/app/api-reference/file-conventions/route-segment-config/ensureStatic#shell). See [Keeping pages static](/docs/app/guides/keeping-pages-static) for a worked example.
Everything above `prefetch()` renders in the App Shell, and everything below renders on a per-link prefetch or on the navigation. Deferral is scoped to the component that awaits it and the tree below: sibling branches render in the shell as usual. Place it above the work to defer, and wrap the component in [`<Suspense>`](https://react.dev/reference/react/Suspense):
```tsx filename="app/dashboard/page.tsx" highlight={25} switcher
......@@ -67,7 +69,7 @@ async function Greeting() {
}
async function Recommendations() {
await prefetch() // everything below renders on a per-link prefetch
await prefetch() // runtime work below renders on a per-link prefetch or navigation
const items = await getRecommendations()
return <List items={items} />
}
......@@ -105,7 +107,7 @@ async function Greeting() {
}
async function Recommendations() {
await prefetch() // everything below renders on a per-link prefetch
await prefetch() // runtime work below renders on a per-link prefetch or navigation
const items = await getRecommendations()
return <List items={items} />
}
......@@ -118,7 +120,7 @@ async function getRecommendations() {
}
```
The greeting reads the session and stays in the App Shell. The recommendations read it too, inside `getRecommendations`, so that read is deferred along with the ranking. Remove `prefetch()` and they become part of the App Shell that every link into the route prefetches.
The greeting reads the session and stays in the App Shell. The recommendations read it too, inside `getRecommendations`, so that read is deferred along with the ranking. Remove `prefetch()` and they become part of the App Shell that every link into the route loads.
Put the directive on a function called below it, as `getRecommendations` does here. Awaiting `prefetch()` inside a cached scope, such as [`use cache`](/docs/app/api-reference/directives/use-cache) or [`use cache: private`](/docs/app/api-reference/directives/use-cache-private), is not allowed.
......@@ -126,17 +128,17 @@ Put the directive on a function called below it, as `getRecommendations` does he
The [`connection()`](/docs/app/api-reference/functions/connection) function waits for a real request. It excludes the code that follows from prerendering and prefetching, making that work request-dependent.
`prefetch()` only excludes the code that follows from the App Shell. It can resolve during a per-link prefetch without making that work request-dependent. A function called after `await prefetch()` can therefore use [`"use cache"`](/docs/app/api-reference/directives/use-cache) and keep its cache lifetime without generating its result for every link into the route.
Awaiting `prefetch()` excludes the code that follows from the App Shell. It can resolve during a per-link prefetch without making that work request-dependent. A function called after `await prefetch()` can therefore use [`"use cache"`](/docs/app/api-reference/directives/use-cache) and keep its cache lifetime without generating its result for every link into the route.
Use `connection()` when the work must run for a real request. Use `prefetch()` when the work is reusable but should only run for a selected per-link prefetch or a navigation.
## When to use it
Reach for it when the content below `prefetch()` is expensive to produce, in compute, in upstream requests, or in latency, and you do not want it generated in the App Shell that every `<Link>` into the route prefetches.
Use `prefetch()` when the content below it is expensive to produce and should not be generated in the App Shell that every `<Link>` into the route loads.
Producing the App Shell does not run that code, so its upstream requests are not issued until a per-link prefetch or the navigation.
Keeping that content out of the shell would otherwise mean leaving it uncached. With `prefetch()` it can be cached with [`use cache`](/docs/app/api-reference/directives/use-cache) or [`use cache: private`](/docs/app/api-reference/directives/use-cache-private), given a lifetime, and deferred to a per-link prefetch or the navigation.
Leaving content uncached also keeps it out of the shell, but gives up its cache lifetime and cannot make it available during a per-link prefetch. With `prefetch()`, the content can be cached with [`use cache`](/docs/app/api-reference/directives/use-cache) or [`use cache: private`](/docs/app/api-reference/directives/use-cache-private), given a lifetime, and deferred to a per-link prefetch or navigation.
Uncached reads, values with a short [`stale`](/docs/app/api-reference/functions/cacheLife#stale) time, and anything behind `params` or `searchParams` are already left out of the shell on their own.
......@@ -147,7 +149,8 @@ When every read of [`cookies()`](/docs/app/api-reference/functions/cookies) and
## Good to know
- The function has no effect on the initial load of a page.
- A call outside a `<Suspense>` boundary surfaces an [Instant Insight](/docs/messages/instant-navigation-stage) in development. It is reported even on a page that is currently prerendered in full, because the same page starts deferring content as soon as it switches to a runtime shell.
- Unlike [`connection()`](/docs/app/api-reference/functions/connection), it does not mark the subtree as request-dependent. Content below `await prefetch()` stays fully cacheable and can be wrapped in [`use cache`](/docs/app/api-reference/directives/use-cache).
- A call outside a `<Suspense>` boundary surfaces an [Instant Insight](/docs/messages/instant-navigation-stage) in development. A fully prerendered route is unaffected, but the insight identifies that the call would defer content without a fallback if the route later requires runtime rendering.
- Calling it inside `use cache`, `use cache: private`, [`unstable_cache()`](/docs/app/api-reference/functions/unstable_cache), [`after()`](/docs/app/api-reference/functions/after), [`generateStaticParams`](/docs/app/api-reference/functions/generate-static-params), or a Client Component throws.
- In a `page` or `layout` that sets the [`prefetch` route segment config](/docs/app/api-reference/file-conventions/route-segment-config/prefetch), import the function under another name, for example `import { prefetch as prefetchStage } from 'next/cache'`, since both are named `prefetch`.
......
......@@ -89,7 +89,7 @@ module.exports = {
#### Keep prefetching the dynamic data
`'partial'` prefetches only the App Shell, which is the route's static and cached content. Uncached dynamic data is no longer prefetched. To keep prefetching content that came down with `prefetch={true}`, work through two steps.
`'partial'` loads only the App Shell, which is the route's static and cached content. Uncached dynamic data is no longer prefetched. To keep prefetching content that came down with `prefetch={true}`, work through two steps.
1. Cache it with [`use cache`](/docs/app/api-reference/directives/use-cache). If the content doesn't depend on the URL, it gets included in the App Shell and that's enough.
2. If it depends on URL data (`params`, `searchParams`), it can't be included in the shared App Shell. With Partial Prefetching enabled, `prefetch={true}` opts the link into [per-link prefetching](/docs/app/guides/optimizing-prefetching), so the cached content can resolve before navigation.
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment