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

Docs/partial prefetching (#94855)

## Summary

- `prefetch.mdx`: corrections, disambiguation and TS signature update
- `runtime-prefetching.mdx`: App Shells section corrections
- `instant-navigation.mdx`: DevTools section re-aligned (mpa/spa split,
panel labels, cold-cache indicator)
- x-refs

## TODO

- [x] `partialPrefetching.mdx` API reference with the three levels of
prefetch
- [x] runtime prefetching journey
parent 5ed0a5c9
...@@ -107,10 +107,12 @@ The `@next/playwright` package provides an [`instant()`](/docs/app/api-reference ...@@ -107,10 +107,12 @@ The `@next/playwright` package provides an [`instant()`](/docs/app/api-reference
### Inspect loading states ### Inspect loading states
The **Navigation Inspector** in the Next.js DevTools freezes the page at the static shell for direct visits and client navigations. Use it as a feedback loop while you develop: is a loading fallback covering too much? Can a `<Suspense>` boundary move closer to the data? See [Maximizing the static shell](/docs/app/getting-started/caching#maximizing-the-static-shell) for the structural pattern. The **Navigation Inspector** in the Next.js DevTools freezes the page at its initial loading state, showing the static shell on direct visits and the prefetched destination on client navigations. Use the inspector to see how much meaningful content lands in the shell.
Pair it with the React DevTools Suspense panel to see exactly which boundary covers which part of the page. See [Visualize loading states with the Next.js DevTools](#visualize-loading-states-with-the-nextjs-devtools) for the workflow. Pair it with the React DevTools Suspense panel to see exactly which boundary covers which part of the page. See [Visualize loading states with the Next.js DevTools](#visualize-loading-states-with-the-nextjs-devtools) for the workflow.
See [Maximizing the static shell](/docs/app/getting-started/caching#maximizing-the-static-shell) for patterns to reduce fallback coverage and pull more content into the shell.
## A page that navigates instantly ## A page that navigates instantly
To see the primitives in action, consider a small store app. Each product has its own page at `/store/[slug]`, reachable from the homepage and from other product pages. The goal is that navigating to and between products is instant. To see the primitives in action, consider a small store app. Each product has its own page at `/store/[slug]`, reachable from the homepage and from other product pages. The goal is that navigating to and between products is instant.
...@@ -214,15 +216,17 @@ const nextConfig: NextConfig = { ...@@ -214,15 +216,17 @@ const nextConfig: NextConfig = {
export default nextConfig export default nextConfig
``` ```
Open the Next.js DevTools and select **Navigation Inspector**, then click **Start Capturing**. While capturing is active: Open the Next.js DevTools and select **Navigation Inspector**, then toggle **Pause on navigations**. The panel shows **Awaiting navigation...** While the toggle is on:
- Refresh the page to freeze the initial static UI generated for the route, before any dynamic data streams in. - Refresh the page to freeze the **static shell**, the route's prerendered UI before any dynamic data streams in. The panel shows **Loading shell** labeled **Page load**, along with the target URL.
- Click a link to freeze the prefetched UI for the destination route. - Click a link to freeze the **prefetched UI** for the destination route. The panel shows **Loading shell** labeled **Client nav**, along with both source and target URLs.
When the UI is frozen, click **Continue Rendering** to let the current navigation finish while keeping the Navigation Inspector in capturing mode. Click **Stop Capturing** when you are done inspecting loading states. When the UI is frozen, click **Resume** to complete the navigation. As long as the **Pause on navigations** toggle stays on, further navigations pause too. Toggle it off when you're done inspecting loading states.
Try refreshing the product page. Two separate fallbacks appear: "Loading product..." and "Checking availability...". On the first visit the cache is cold and both fallbacks are visible. Navigate to the page again and the product name appears immediately from cache. Try refreshing the product page. Two separate fallbacks appear: "Loading product..." and "Checking availability...". On the first visit the cache is cold and both fallbacks are visible. Navigate to the page again and the product name appears immediately from cache.
> **Good to know**: When `next dev` renders against an empty cache, the dev indicator turns orange ("Rendering (cold cache)") and leaves a dismissible "Cold cache" badge afterward. A "Cache disabled" variant appears when caches are bypassed. Reload once caches are warm to see a production-representative view.
{/* TODO: screenshot — Navigation Inspector frozen at the static shell on a page refresh, showing both "Loading product..." and "Checking availability..." fallbacks */} {/* TODO: screenshot — Navigation Inspector frozen at the static shell on a page refresh, showing both "Loading product..." and "Checking availability..." fallbacks */}
Now click a link from `/store/shoes` to `/store/hats`. The product name and price appear immediately (cached). "Checking availability..." shows where inventory will stream in. Now click a link from `/store/shoes` to `/store/hats`. The product name and price appear immediately (cached). "Checking availability..." shows where inventory will stream in.
......
--- ---
title: Runtime prefetching title: Runtime prefetching
description: Extend the static shell with personalized content using the prefetch segment config and per-session caching directives. description: Extend the App Shell with personalized content using the prefetch segment config and per-session caching directives.
nav_title: Runtime prefetching nav_title: Runtime prefetching
version: experimental version: experimental
related: related:
...@@ -14,9 +14,9 @@ related: ...@@ -14,9 +14,9 @@ related:
- app/guides/instant-navigation - app/guides/instant-navigation
--- ---
The router prefetches the static shell of every visible `<Link>`. Runtime prefetching lets it also include content that depends on the request: cookies, headers, the full URL, `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. With runtime prefetching, the prerender walks past static and cached content before the click, stopping at boundaries that wrap uncached reads. 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.
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. That cost only pays off if your route's caching structure lets the prerender resolve past the static shell. 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.
## What runtime prefetching does ## What runtime prefetching does
...@@ -60,9 +60,9 @@ export default function CoursesPage() { ...@@ -60,9 +60,9 @@ export default function CoursesPage() {
} }
``` ```
Without `prefetch = 'allow-runtime'`, the router prefetches the static shell. `<h1>` and `<FeaturedCourses>` are in it; both `<Suspense>` boundaries render to their fallbacks. After the click, `<EnrolledBadge>` and `<LiveEnrollment>` stream in. 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.
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, past the static 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. 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.
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 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**.
...@@ -80,7 +80,7 @@ Take a dashboard layout with a nav that depends on request data. Without runtime ...@@ -80,7 +80,7 @@ Take a dashboard layout with a nav that depends on request data. Without runtime
export const prefetch = 'allow-runtime' export const prefetch = 'allow-runtime'
``` ```
The route still needs a valid static shell, so `<UserNav>` stays behind a `<Suspense>` boundary: The route still needs a valid prerender, so `<UserNav>` stays behind a `<Suspense>` boundary:
```tsx filename="app/dashboard/layout.tsx" ```tsx filename="app/dashboard/layout.tsx"
import { Suspense } from 'react' import { Suspense } from 'react'
...@@ -163,9 +163,9 @@ Use it on routes where: ...@@ -163,9 +163,9 @@ Use it on routes where:
- That chunk has a known cache lifetime (it can be expressed with `"use cache"` or `"use cache: private"`) - That chunk has a known cache lifetime (it can be expressed with `"use cache"` or `"use cache: private"`)
- The traffic justifies the per-link server invocation - The traffic justifies the per-link server invocation
Skip it when the prefetch can't produce a better UI than the static 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: 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 static shell already gets you instant. - The route has little or no runtime-data dependency. The App Shell already gets you 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 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. - The route is rarely navigated to. You pay per visible link, regardless of click-through.
...@@ -175,9 +175,9 @@ A per-link runtime prefetch only helps the navigations where it fires before the ...@@ -175,9 +175,9 @@ A per-link runtime prefetch only helps the navigations where it fires before the
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. 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 when Partial Prefetching is enabled: 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={3} ```ts filename="next.config.ts" highlight={5}
import type { NextConfig } from 'next' import type { NextConfig } from 'next'
const nextConfig: NextConfig = { const nextConfig: NextConfig = {
...@@ -188,16 +188,18 @@ const nextConfig: NextConfig = { ...@@ -188,16 +188,18 @@ const nextConfig: NextConfig = {
export default nextConfig export default nextConfig
``` ```
Every Cache Components route has an instant floor. N links to the same route share one prefetched App Shell, and rendering a `<Link>` is effectively free unless `prefetch={true}` is set on the Link, which upgrades to the per-link prefetch. Opting a route into [`prefetch = 'allow-runtime'`](/docs/app/api-reference/file-conventions/route-segment-config/prefetch#allow-runtime) further upgrades those per-link prefetches to runtime prerenders with request data. 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.
Compared with per-link runtime prefetching: > **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 Shell | Per-link runtime prefetch (`allow-runtime`) | App Shells vs runtime prefetches:
| ------- | ----------------------------------------- | ------------------------------------------- |
| Scope | One per route | One per visible link | | | App Shell | Per-link runtime prefetch (`allow-runtime`) |
| Content | Route shell, reusable across param values | Concrete request prerender, param-specific | | ------- | -------------------------------------------- | ------------------------------------------- |
| Cost | Bounded by route count | Bounded by visible-link count | | Scope | One per route | One per visible `<Link prefetch={true}>` |
| Role | Default: every route has an instant floor | Upgrade: more rendered before click | | 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 |
## Next steps ## Next steps
......
...@@ -9,14 +9,13 @@ related: ...@@ -9,14 +9,13 @@ related:
- app/api-reference/file-conventions/route-segment-config/instant - app/api-reference/file-conventions/route-segment-config/instant
--- ---
The `prefetch` route segment config controls how a segment is prefetched during client-side navigation. The default (`'auto'`) lets Next.js manage the strategy on your behalf — today that always means a static prefetch. The other options let you declare which prefetch behavior is appropriate for the segment. Use them with care, since they can affect both navigation latency and prefetch cost. The `prefetch` route segment config controls how a segment is prefetched during client-side navigation. By default, the framework manages the strategy based on the app's [`partialPrefetching`](/docs/app/api-reference/config/next-config-js/partialPrefetching) setting. To override per segment, set this export to one of the values below.
When you do set this export, consider pairing it with [`instant`](/docs/app/api-reference/file-conventions/route-segment-config/instant) so validation can confirm that navigations to this segment actually produce an instant UI from the prefetched data. This is especially important for runtime prefetching.
> **Good to know**: > **Good to know**:
> >
> - The `prefetch` export only works when [`cacheComponents`](/docs/app/api-reference/config/next-config-js/cacheComponents) is enabled. > - The `prefetch` export only works when [`cacheComponents`](/docs/app/api-reference/config/next-config-js/cacheComponents) is enabled.
> - `prefetch` cannot be used when the segment is a Client Component. > - `prefetch` cannot be used when the segment is a Client Component.
> - The meaningful values to set are `'allow-runtime'`, `'partial'`, and `'force-disabled'`. `'auto'` is the default and is equivalent to omitting the export; don't write `prefetch = 'auto'` explicitly.
```tsx filename="layout.tsx | page.tsx" switcher ```tsx filename="layout.tsx | page.tsx" switcher
export const prefetch = 'allow-runtime' export const prefetch = 'allow-runtime'
...@@ -36,19 +35,11 @@ export default function Page() { ...@@ -36,19 +35,11 @@ export default function Page() {
## Options ## Options
### `'auto'` (default)
Lets Next.js manage prefetching for this segment. Today this always means a static prefetch — to permit runtime prefetching, opt in explicitly with [`'allow-runtime'`](#allow-runtime).
A future release will use [`instant`](/docs/app/api-reference/file-conventions/route-segment-config/instant) validation to choose between static and runtime prefetching automatically. Leaving the default in place means your app will pick up that improvement without code changes.
You typically don't need to set this explicitly — omitting the export has the same effect.
### `'allow-runtime'` ### `'allow-runtime'`
Allows Next.js to prefetch this segment at runtime. Today, setting this option causes Next.js to issue a runtime prefetch request, so the server can render a fresh response that includes runtime data like cookies, headers, and search params. Use this for personalized content when the latency and cost of runtime prefetching are appropriate for the segment. Allows Next.js to prefetch this segment at runtime. Today, setting this option causes Next.js to issue a runtime prefetch request, so the server can render a fresh response that includes runtime data like cookies, headers, and search params. Use this for personalized content when the latency and cost of runtime prefetching are appropriate for the segment.
> **Good to know**: When Next.js runtime-prefetches a segment, all downstream segments are included in the same runtime prefetch request. This means segments deeper in the tree that are configured with `'force-static'` or `'force-disabled'` will still be prefetched as part of the runtime response. > **Good to know**: When Next.js runtime-prefetches a segment, all downstream segments are included in the same runtime prefetch request. Segments deeper in the tree that are configured with `'force-disabled'` will still be prefetched as part of the runtime response.
```tsx filename="page.tsx" ```tsx filename="page.tsx"
export const prefetch = 'allow-runtime' export const prefetch = 'allow-runtime'
...@@ -64,10 +55,6 @@ Use this for incremental adoption when you can't enable `partialPrefetching` for ...@@ -64,10 +55,6 @@ Use this for incremental adoption when you can't enable `partialPrefetching` for
export const prefetch = 'partial' export const prefetch = 'partial'
``` ```
### `'force-static'`
Always prefetch this segment statically, even if it has not been validated with `instant`. Use this when you know the segment produces a valid static shell but do not want to set up instant validation.
### `'force-disabled'` ### `'force-disabled'`
Never prefetch this segment. The client will not request segment data ahead of navigation. Use this for segments where prefetching would be wasteful, for example pages behind authentication that are rarely visited. Never prefetch this segment. The client will not request segment data ahead of navigation. Use this for segments where prefetching would be wasteful, for example pages behind authentication that are rarely visited.
...@@ -76,22 +63,22 @@ Never prefetch this segment. The client will not request segment data ahead of n ...@@ -76,22 +63,22 @@ Never prefetch this segment. The client will not request segment data ahead of n
## Relationship with the `<Link prefetch>` prop ## Relationship with the `<Link prefetch>` prop
The `prefetch` segment config and the [`<Link prefetch>` prop](/docs/app/api-reference/components/link#prefetch) control different aspects of prefetching: A prefetch starts with a `<Link>` that expresses intent (should this destination be prefetched, and how eagerly), and ends at a segment that sets a cost ceiling (how much work is it OK to do ahead of time, for any link that points here).
A destination can't know which links target it, so the segment config caps what any `<Link prefetch={true}>` pulls:
- [`'allow-runtime'`](#allow-runtime): App Shell plus runtime data (cookies, headers, search params).
- [`'partial'`](#partial): App Shell only.
- [`'force-disabled'`](#force-disabled): skip segment data entirely.
- The **segment config** informs Next.js about a segment's caching characteristics — whether its data can be prefetched statically, is suitable for a runtime prefetch with the user's session, or should be skipped entirely. This applies to the segment regardless of which link points to it. `<Link prefetch={false}>` skips prefetching at the link level regardless of how the destination is configured.
- The **`<Link prefetch>` prop** reflects the anticipated intent of a specific link on a specific page. A link that users rarely click can be deprioritized with `prefetch={false}`, independent of how the destination segments are configured.
In general, both of these are special circumstances. The default behavior — where Next.js manages prefetching for you — is optimized to provide a good navigation experience without manual configuration. > **Good to know**: A prefetch may be served from a CDN cache, reuse a cached App Shell, or run a fresh server render. Wider prefetches lean toward fresh server work and cost more server CPU per page view.
## TypeScript ## TypeScript
```tsx ```tsx
type Prefetch = type Prefetch = 'auto' | 'allow-runtime' | 'partial' | 'force-disabled'
| 'auto'
| 'allow-runtime'
| 'partial'
| 'force-static'
| 'force-disabled'
export const prefetch: Prefetch = 'allow-runtime' export const prefetch: Prefetch = 'allow-runtime'
``` ```
......
...@@ -44,13 +44,17 @@ module.exports = { ...@@ -44,13 +44,17 @@ module.exports = {
## How prefetches resolve ## How prefetches resolve
With `partialPrefetching` enabled: Before Partial Prefetching, Next.js prefetched per visible link: a page with N links to N routes produced ~N route prefetches as those links entered the viewport.
- **Plain `<Link>`** prefetches the route's [App Shell](/docs/app/glossary#app-shell), shared across every link to the route. With `partialPrefetching: true`, Next.js prefetches one reusable [App Shell](/docs/app/glossary#app-shell) per route instead. The shell carries the route's rendered output minus per-link data; specifics like params and search-bound data fill in after navigation. Shells are cached on the client, so a route is fetched once even if many links on the page point at it.
- **`<Link prefetch={true}>`** prefetches the route's static shell with its cached content.
- **`<Link prefetch={true}>` + per-segment `prefetch = 'allow-runtime'`** prefetches a [runtime prerender](/docs/app/guides/runtime-prefetching) that includes cached content gated by runtime data.
See the [runtime prefetching guide](/docs/app/guides/runtime-prefetching) for the per-link behavior in detail. 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.
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 includes runtime data like cookies, headers, and search params.
> **Good to know**: If you use `<Link prefetch={true}>` to a route that hasn't opted into Partial Prefetching, a dev console error suggests enabling `partialPrefetching` app-wide or `prefetch = 'partial'` on the segment. The [dev warning Insight](/docs/messages/instant-link-prefetch-partial) covers each fix in detail.
## Per-segment overrides ## Per-segment overrides
......
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