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
This diff is collapsed.
# 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})`)
}
}
This diff is collapsed.
#!/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
This diff is collapsed.
......@@ -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'`.
......
This diff is collapsed.
......@@ -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).
......
......@@ -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: 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