Unverified Commit c3d1e893 authored by Joseph's avatar Joseph Committed by GitHub

docs: runtime prefetching update (#95564)

Sync the runtime prefetching guide with latest App Shell changes
parent 4a4590a3
......@@ -83,7 +83,7 @@ export default function CategoryLayout(props: LayoutProps<'/[category]'>) {
}
```
Notice that `CategoryLayout` does not `await props.params` itself. Instead, it passes the `params` promise to `CategoryHeader` inside `<Suspense>`. The `await` happens inside the boundary, so for unknown categories Next.js can still generate the App Shell.
Notice that `CategoryLayout` does not `await props.params` itself. Instead, it passes the `params` promise to `CategoryHeader` inside `<Suspense>`. The `await` happens inside the boundary, so for unknown categories Next.js can still generate the App Shell. Keep the read inside the boundary even for the categories `generateStaticParams` covers. A statically known param still belongs to one URL, so awaiting it above the Suspense boundary would tie this layout's App Shell to that URL. See [Instant navigation](/docs/app/guides/instant-navigation) for structuring routes this way.
The product page prerenders one product per category. `generateStaticParams` receives the parent `category` param:
......
......@@ -50,7 +50,7 @@ With Cache Components, **caching directives** (`"use cache"` and its variants) a
> **Good to know:** A fallback may access `cookies()`, `headers()`, or the full URL. At build time, the fallback itself suspends, and a `<Suspense>` boundary further up the tree is needed. With [runtime prefetching](/docs/app/guides/runtime-prefetching), the information is available and such a fallback becomes part of the instant UI. Cached values like timestamps or data fetches can sit directly inside the fallback.
Next.js can also generate an [**App Shell**](/docs/app/glossary#app-shell) per route: a fallback that renders instantly during client navigations when nothing else is ready. See [App Shells](/docs/app/guides/runtime-prefetching#app-shells) for how to enable them and how they pair with runtime prefetching.
Next.js can also generate an [**App Shell**](/docs/app/glossary#app-shell) per route: a fallback that renders instantly during client navigations when nothing else is ready. [Runtime prefetching](/docs/app/guides/runtime-prefetching) builds on it, resolving a link's URL data on top.
### Tune what `<Link>` prefetches
......
......@@ -205,13 +205,15 @@ Next.js maintains a small task queue, which prefetches in the following order:
The scheduler prioritizes likely navigations while minimizing unused downloads.
### Partial Prerendering (PPR)
### Cache Components
When PPR is enabled, a page is divided into a [static shell](/docs/app/guides/streaming#the-static-shell) and a streamed dynamic section:
With [Cache Components](/docs/app/getting-started/caching) enabled, the prefetching strategy uses an [App Shell](/docs/app/glossary#app-shell) to make client navigations instant:
- The shell, which can be prefetched, streams immediately
- Uncached data streams when ready
- Data invalidations (`revalidateTag`, `revalidatePath`) silently refresh associated prefetches
- The App Shell holds the route's static and session output.
- Uncached data streams in when ready.
- Data invalidations (`revalidateTag`, `revalidatePath`) silently refresh associated prefetches.
A link can also resolve its URL data (`searchParams`, `params`) at prefetch time. See [Runtime prefetching](/docs/app/guides/runtime-prefetching).
## Troubleshooting
......
---
title: Runtime prefetching
description: Extend the App Shell with personalized content using the prefetch segment config and per-session caching directives.
description: Prefetch URL data alongside the App Shell using the prefetch segment config and per-session caching directives.
nav_title: Runtime prefetching
version: experimental
related:
title: Learn more
description: Validate your structure and dive into caching primitives.
description: Validate your structure and review the caching primitives.
links:
- app/api-reference/config/next-config-js/partialPrefetching
- 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
---
The router prefetches an [App Shell](/docs/app/glossary#app-shell) per route as visible `<Link>` components enter the viewport. Runtime prefetching lets the prefetch also include content that depends on the request: cookies, headers, `searchParams`, and `params` not resolved by [`generateStaticParams`](/docs/app/api-reference/functions/generate-static-params). On a direct visit, the `<Suspense>` boundaries around runtime data render their fallbacks and the content streams in. Uncached reads stay behind their fallback boundaries either way.
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.
This guide assumes you've structured your route for instant navigation. If you haven't, start with the [Instant navigation guide](/docs/app/guides/instant-navigation) to validate the route's caching structure first. Runtime prefetching costs a per-link server invocation. It only pays off when there's content past the App Shell worth resolving before the click.
The regular App Router prefetches a route all or nothing: the full route when it's static, and nothing for a dynamic route without a [`loading.js`](/docs/app/api-reference/file-conventions/loading).
[Cache Components](/docs/app/getting-started/caching) takes a different approach and produces an [**App Shell**](/docs/app/glossary#app-shell) for every route. The shell contains the route's static output, and for a route that reads [`cookies()`](/docs/app/api-reference/functions/cookies) or [`headers()`](/docs/app/api-reference/functions/headers) (session data), it can also contain UI gated behind that session data.
Prefetching one reusable shell per route, rather than a separate prefetch per link, is [**Partial Prefetching**](/docs/app/api-reference/config/next-config-js/partialPrefetching). Any number of links to the same route share that one shell, fetched once as a [`<Link>`](/docs/app/api-reference/components/link) enters the viewport and reused for the rest.
The shell cannot carry data that varies per link: [`searchParams`](/docs/app/api-reference/file-conventions/page#searchparams-optional) and [`params`](/docs/app/api-reference/file-conventions/page#params-optional), the route's [URL data](/docs/app/glossary#url-data). **Runtime prefetching** resolves that URL data at prefetch time, ready before the click rather than streaming in after it.
This guide assumes [Cache Components](/docs/app/getting-started/caching) with [`partialPrefetching`](/docs/app/api-reference/config/next-config-js/partialPrefetching) enabled:
```ts filename="next.config.ts" highlight={4,5}
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
cacheComponents: true,
partialPrefetching: true,
}
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.
## What runtime prefetching does
A user on `/` sees a [`<Link>`](/docs/app/api-reference/components/link) to `/courses`. The destination mixes four kinds of content: a static heading, an `<EnrolledBadge>` that reads the session cookie, a cached `<FeaturedCourses>` list, and a `<LiveEnrollment>` count that has to be fresh on every request.
Runtime prefetching takes two opt-ins: links to the route use `<Link prefetch={true}>`, and the destination route sets [`prefetch = 'allow-runtime'`](/docs/app/api-reference/file-conventions/route-segment-config/prefetch#allow-runtime).
```tsx filename="app/layout.tsx"
A user on `/` sees links to `/search?q=react` and `/search?q=next`, each opting in with `prefetch={true}`:
```tsx filename="app/page.tsx"
import Link from 'next/link'
export default function RootLayout({ children }: LayoutProps<'/'>) {
export default function Home() {
return (
<html>
<body>
<nav>
<Link href="/courses">Courses</Link>
</nav>
{children}
</body>
</html>
<nav>
<Link href="/search?q=react" prefetch={true}>
React
</Link>
<Link href="/search?q=next" prefetch={true}>
Next.js
</Link>
</nav>
)
}
```
```tsx filename="app/courses/page.tsx"
The destination renders a static heading and a `<Results>` list whose contents depend on the query. Each query is cached, computed once and reused.
```tsx filename="app/search/page.tsx"
import { Suspense } from 'react'
export const prefetch = 'allow-runtime'
export default function CoursesPage() {
export default function SearchPage({ searchParams }: PageProps<'/search'>) {
return (
<>
<h1>Courses</h1>
<Suspense fallback={<BadgeFallback />}>
<EnrolledBadge /> {/* reads the session cookie */}
</Suspense>
<FeaturedCourses /> {/* 'use cache' */}
<Suspense fallback={<Loading />}>
<LiveEnrollment /> {/* uncached, fresh per request */}
<h1>Search</h1>
<Suspense fallback={<ResultsSkeleton />}>
<Results searchParams={searchParams} />
</Suspense>
</>
)
}
async function Results({
searchParams,
}: {
searchParams: PageProps<'/search'>['searchParams']
}) {
const { q } = await searchParams
return <ResultList items={await search(q)} />
}
async function search(q: string) {
'use cache'
return db.search(q)
}
```
Without `prefetch = 'allow-runtime'`, the App Shell renders `<h1>` and `<FeaturedCourses>` directly, while the two `<Suspense>` boundaries show their fallbacks. After the click, `<EnrolledBadge>` and `<LiveEnrollment>` stream in.
Without `prefetch = 'allow-runtime'`, the App Shell renders `<h1>` and shows the `<Results>` fallback. The query resolves after the click and streams the results in.
When [`prefetch = 'allow-runtime'`](/docs/app/api-reference/file-conventions/route-segment-config/prefetch) is set on the route, the router prefetches a prerender of `/courses` that includes request data, beyond what's in the App Shell. `<EnrolledBadge>` resolves because the session cookie is available at prefetch time. `<LiveEnrollment>` still sits behind its fallback because no prerender can know its current value. After the click, only `<LiveEnrollment>` streams in.
With [`prefetch = 'allow-runtime'`](/docs/app/api-reference/file-conventions/route-segment-config/prefetch) on the route, 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)` fills in from there. On the click, the results render immediately, with no fallback.
The prerender advances through anything that's static or cached, then stops at uncached reads and falls back to the surrounding `<Suspense>` boundary. The boundary is already in place from your **instant-nav validation**.
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).
The result is a **runtime prerender**: more of the page is already rendered before the user clicks, with fewer loading spinners.
More of the page is rendered before the user clicks, with fewer loading states.
Generating the runtime prerender costs **a server invocation per prefetchable link**, so it is opt-in per route.
Generating it costs **a server invocation per prefetchable link**, so it is opt-in per route.
> **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.
## Example: a dashboard layout
Like `searchParams`, `params` needs a `<Suspense>` boundary, even when the values are predefined by [`generateStaticParams`](/docs/app/api-reference/functions/generate-static-params). A statically known param still belongs to one URL. Runtime prefetching resolves the values `generateStaticParams` does not cover.
Take a dashboard layout with a nav that depends on request data. Without runtime prefetching, `<UserNav>` always streams in behind a `<Suspense>` fallback after navigation, even though the cookie that determines its content is already known when the prefetch fires. With runtime prefetching, the router prefetches a prerender that resolves `<UserNav>` before the click:
## Session data resolves in the shell
```tsx filename="app/dashboard/layout.tsx"
export const prefetch = 'allow-runtime'
```
Runtime prefetching, via `allow-runtime`, is for URL data. Session data is handled separately: a route that reads `cookies()` or `headers()`, including through `"use cache: private"`, gets an App Shell that includes its session data, cached per session on the client and ready on navigation without `allow-runtime`.
The route still needs a valid prerender, so `<UserNav>` stays behind a `<Suspense>` boundary:
A lookup based on session data needs a cache lifetime, the same way `search(q)` did for the URL. Take a dashboard nav that reads a cookie, then looks up content based on it:
```tsx filename="app/dashboard/layout.tsx"
import { Suspense } from 'react'
......@@ -99,11 +134,14 @@ export default function DashboardLayout({
}
```
`<UserNav>` reads a cookie, then looks up data based on it. The challenge is that `"use cache"` can't read `cookies()` inside the cached function. Two patterns handle this: **extract and pass** when the lookup result is shared across many users, and `"use cache: private"` when it's tied to a specific user.
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:
- **Extract and pass** when the lookup result is shared across many sessions.
- **`"use cache: private"`** when it is tied to one.
### Extract and pass
Read the cookie outside the cached function and pass the value in as an argument. `cookies()` stays outside the cache scope, the argument crosses the boundary, and the cached function has a deterministic signature. The cache entry is keyed on that argument; if many users share the value, they share the entry.
Read the cookie outside the cached function and pass the value in as an argument. The `cookies()` call stays outside the cache scope, the argument crosses the boundary, and the cached function has a deterministic signature. The cache entry is keyed on that argument, and sessions that share the value share the entry.
```tsx filename="app/dashboard/user-nav.tsx"
import { cookies } from 'next/headers'
......@@ -128,13 +166,13 @@ async function getTopics(team: string | undefined) {
}
```
On a direct visit, `<UserNav>` streams in behind the fallback. With runtime prefetching, the prerender resolves `<UserNav>` before the click because the team cookie is available at prefetch time. Users on the same team share the cache entry, so traffic to the underlying data scales with team count, not user count.
On a direct visit, `<UserNav>` shows its fallback until the lookup resolves. On navigation, the App Shell has already resolved it, because the team cookie is session data the shell can read. Because sessions on the same team share the cache entry, traffic to the underlying data scales with team count, not session count.
Anything without a caching directive still streams in after navigation. The runtime prerender is not a full server render. It advances only as far as the caching structure allows.
Anything without a caching directive still streams in after navigation. A shell holds only what can be prepared ahead of the navigation, not the whole page. It advances only as far as the caching structure allows.
### `"use cache: private"`
When the lookup is tied to a specific user, use [`"use cache: private"`](/docs/app/api-reference/directives/use-cache-private). It assigns a cache lifetime to a function that reads cookies, headers, or other runtime data directly. Results are cached in the browser only, so the cache is per-user by definition.
When the lookup is tied to a single session, use [`"use cache: private"`](/docs/app/api-reference/directives/use-cache-private). It assigns a cache lifetime to a function that reads cookies, headers, or other runtime data directly. Results are cached in the browser only, scoped to that session.
```tsx filename="app/dashboard/user-nav.tsx"
import { cookies } from 'next/headers'
......@@ -151,55 +189,32 @@ async function getUser() {
}
```
`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"`. 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.
Everything inside the scope shares the same lifetime, so colocate `"use cache: private"` as close to the runtime data access as possible.
Everything inside the scope shares the same lifetime. Colocate `"use cache: private"` as close to the runtime data access as possible.
## When to reach for runtime prefetching
## Per-link prefetching trade-offs
Use it on routes where:
- A useful chunk of the page depends on request data: cookies, headers, the full URL, `searchParams`, or `params` not resolved by [`generateStaticParams`](/docs/app/api-reference/functions/generate-static-params)
- That chunk has a known cache lifetime (it can be expressed with `"use cache"` or `"use cache: private"`)
- Part of the component tree depends on URL data: the full URL, `searchParams`, or `params` not resolved by [`generateStaticParams`](/docs/app/api-reference/functions/generate-static-params)
- That part of the tree has a known cache lifetime (it can be expressed with `"use cache"` or `"use cache: private"`)
- The traffic justifies the per-link server invocation
Skip it when the prefetch can't produce a better UI than the App Shell. Each visible `<Link>` to a route with `'allow-runtime'` wakes a server, and that cost only pays off if more of the page is ready before the click:
- The route has little or no runtime-data dependency. The App Shell already gets you instant.
- The route has little or no URL-data dependency. The App Shell already makes the navigation instant.
- The dependent content has to be fresh on every request. The prerender stops at the same `<Suspense>` fallback, so the user sees the same UI either way.
- The route is rarely navigated to. You pay per visible link, regardless of click-through.
## App Shells
A per-link runtime prefetch only helps the navigations where it fires before the click and completes before the click. On a slow connection, on a feed of many links, or on a direct visit, the per-link prefetch may not yet exist when the user navigates. Without something to fall back on, the navigation blocks until the server responds.
The [**App Shell**](/docs/app/glossary#app-shell) closes that gap. It's a per-route prerender, deduped across every link to the same route, generated and prefetched once per route rather than once per visible link.
App Shells are on by default with Cache Components. Pairing with `partialPrefetching: true` makes them the prefetch baseline for every route:
```ts filename="next.config.ts" highlight={5}
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
cacheComponents: true,
partialPrefetching: true,
}
export default nextConfig
```
N links to the same route share one prefetched App Shell, so rendering a `<Link>` is effectively free. To prefetch more than the shell (including request data like cookies, headers, params, and `searchParams`), opt the destination into [`prefetch = 'allow-runtime'`](/docs/app/api-reference/file-conventions/route-segment-config/prefetch#allow-runtime) and use `<Link prefetch={true}>` on the link side.
> **Good to know**: Routes that read `cookies()` or `headers()` produce an App Shell that includes session data. The framework auto-detects this, and the shell is cached per session on the client, not shared across users.
App Shells vs runtime prefetches:
A per-link runtime 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. That shell is the reliable baseline, and runtime prefetching only layers on top when it arrives in time.
| | App Shell | Per-link runtime prefetch (`allow-runtime`) |
| ------- | -------------------------------------------- | ------------------------------------------- |
| Scope | One per route | One per visible `<Link prefetch={true}>` |
| Content | Route's rendered output minus per-link data | Same, plus request data resolved |
| Cost | Bounded by route count | Bounded by visible-link count |
| Role | Every Cache Components route's instant floor | Upgrade: more rendered before click |
| | App Shell | Per-link runtime prefetch with `allow-runtime` |
| ------- | ------------------------------------------- | ---------------------------------------------- |
| 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 | Every route's instant floor | Upgrade: more rendered before click |
## Next steps
......
......@@ -50,7 +50,7 @@ With `partialPrefetching: true`, Next.js prefetches one reusable [App Shell](/do
The pattern is similar to per-route code splitting in single-page apps: one artifact per route, shared by every link that points to it.
> **Good to know**: Routes that read `cookies()` or `headers()` produce an App Shell that includes session data. The framework auto-detects this, and the shell is cached per session on the client, not shared across users.
> **Good to know**: Routes that read `cookies()` or `headers()` produce an App Shell that includes session data. The framework auto-detects this and caches the shell per session on the client.
A link can ask for more than the App Shell with [`<Link prefetch={true}>`](/docs/app/api-reference/components/link#prefetch). If the destination opts into [`prefetch = 'allow-runtime'`](/docs/app/api-reference/file-conventions/route-segment-config/prefetch#allow-runtime), the prefetch also resolves per-link runtime data like `params`, `searchParams`, and the full URL.
......
......@@ -12,7 +12,7 @@ The Next.js router introduced in version 13, built on top of React Server Compon
## App Shell
A per-route prerender containing the parts of a page that don't depend on URL-specific data. Routes that read `cookies()` or `headers()` produce a session-personalized variant, cached per session on the client. Used as the prefetch payload during client navigations, the loading state during [runtime prefetching](/docs/app/guides/runtime-prefetching), and the fallback for [ISR with Cache Components](/docs/app/guides/incremental-static-regeneration-cache-components).
A per-route prerender containing the parts of a page that don't depend on URL data. Routes that read `cookies()` or `headers()` produce one that also includes session data, cached per session on the client. Used as the prefetch payload during client navigations, the loading state during [runtime prefetching](/docs/app/guides/runtime-prefetching), and the fallback for [ISR with Cache Components](/docs/app/guides/incremental-static-regeneration-cache-components).
# B
......
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