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

docs: runtime prefetching -> optimizing prefetching (#96934)

With the latest GA changes, when using Cache Components with Partial
Prefetching:

>  prefetch={true} turns on prefetching

These changes try to align around that idea.

- runtime prefetching guide is now about optimizing
- various changes in prose across docs
- even fix an error page for pages router, which had a broad title

---------
Co-authored-by: 's avatarAurora Scharff <aurora.sofie@gmail.com>
parent 90747a9e
...@@ -47,7 +47,7 @@ The [`use cache`](/docs/app/api-reference/directives/use-cache) directive caches ...@@ -47,7 +47,7 @@ The [`use cache`](/docs/app/api-reference/directives/use-cache) directive caches
- **Data-level**: Cache a function that fetches or computes data (e.g., `getProducts()`, `getUser(id)`) - **Data-level**: Cache a function that fetches or computes data (e.g., `getProducts()`, `getUser(id)`)
- **UI-level**: Cache an entire component or page (e.g., `async function BlogPosts()`) - **UI-level**: Cache an entire component or page (e.g., `async function BlogPosts()`)
A cache directive gives a result a lifetime, information Next.js uses to apply rendering optimizations. See [Prerendering](#prerendering) for how cached results become part of the static shell and may be included in a [prefetch](#runtime-prefetching). A cache directive gives a result a lifetime, information Next.js uses to apply rendering optimizations. See [Prerendering](#prerendering) for how cached results become part of the static shell and may be included in a [prefetch](#prefetching).
> **Good to know:** We recommend pairing every cache directive with a [`cacheLife`](/docs/app/api-reference/functions/cacheLife). Without one, the implicit `default` profile applies. > **Good to know:** We recommend pairing every cache directive with a [`cacheLife`](/docs/app/api-reference/functions/cacheLife). Without one, the implicit `default` profile applies.
...@@ -197,7 +197,7 @@ A runtime API access without `<Suspense>` surfaces the same **blocking-route** i ...@@ -197,7 +197,7 @@ A runtime API access without `<Suspense>` surfaces the same **blocking-route** i
/> />
</FixCardGrid> </FixCardGrid>
Runtime-dependent data can still be given a cache lifetime with [`"use cache: private"`](/docs/app/api-reference/directives/use-cache-private), another variant that ships with Cache Components. It gives a lifetime to a function that reads cookies, headers, or `searchParams` directly, so it can be included in a [prefetch](#runtime-prefetching). Runtime-dependent data can still be given a cache lifetime with [`"use cache: private"`](/docs/app/api-reference/directives/use-cache-private), another variant that ships with Cache Components. It gives a lifetime to a function that reads cookies, headers, or `searchParams` directly, so it can be included in a [prefetch](#prefetching).
The following section shows an alternative to `use cache: private`: extracting a runtime value and passing it to a shared cached function. The following section shows an alternative to `use cache: private`: extracting a runtime value and passing it to a shared cached function.
...@@ -236,7 +236,7 @@ At request time, `<CachedContent />` executes if no matching cache entry is foun ...@@ -236,7 +236,7 @@ At request time, `<CachedContent />` executes if no matching cache entry is foun
> **Good to know:** Because `<CachedContent />` is gated behind request data, it isn't added to the prerendered static shell. At runtime it's cached [in-memory](/docs/app/api-reference/directives/use-cache#runtime-caching-considerations) by default, which doesn't persist across serverless requests, so it may re-evaluate on each request. Reach for [`'use cache: remote'`](/docs/app/api-reference/directives/use-cache-remote) for durable, shared caching. > **Good to know:** Because `<CachedContent />` is gated behind request data, it isn't added to the prerendered static shell. At runtime it's cached [in-memory](/docs/app/api-reference/directives/use-cache#runtime-caching-considerations) by default, which doesn't persist across serverless requests, so it may re-evaluate on each request. Reach for [`'use cache: remote'`](/docs/app/api-reference/directives/use-cache-remote) for durable, shared caching.
With this pattern, [runtime prefetching](#runtime-prefetching) can prerender `<CachedContent />` with the user's actual session during a client transition and have the result ready before the click. This works even when server-side entries rarely survive between requests, because the lifetime you assign is what lets the result join the prefetch, where the client treats it as fresh for its [`cacheLife`](/docs/app/api-reference/functions/cacheLife) `stale` window. With this pattern, [prefetching](#prefetching) can prerender `<CachedContent />` with the user's actual session during a client transition and have the result ready before the click. This works even when server-side entries rarely survive between requests, because the lifetime you assign is what lets the result join the prefetch, where the client treats it as fresh for its [`cacheLife`](/docs/app/api-reference/functions/cacheLife) `stale` window.
## Static, cached, and streaming ## Static, cached, and streaming
...@@ -469,7 +469,7 @@ Next.js requires you to explicitly handle components that can't complete during ...@@ -469,7 +469,7 @@ Next.js requires you to explicitly handle components that can't complete during
### Maximizing the static shell ### Maximizing the static shell
The deeper your async work sits in the tree, the more of the page can be prerendered. This is the structural pattern Cache Components rewards: a general practice worth applying everywhere, and the foundation for the instant navigation and runtime prefetching that follow. It applies to all [runtime APIs](#working-with-runtime-apis) and async operations like data fetches. The deeper your async work sits in the tree, the more of the page can be prerendered. This is the structural pattern Cache Components rewards: a general practice worth applying everywhere, and the foundation for the instant navigation and prefetching that follow. It applies to all [runtime APIs](#working-with-runtime-apis) and async operations like data fetches.
Consider a layout that destructures `params` at the top level: Consider a layout that destructures `params` at the top level:
...@@ -531,17 +531,17 @@ Cache Components shipped in 16.0.0 with verification that direct visits to a rou ...@@ -531,17 +531,17 @@ Cache Components shipped in 16.0.0 with verification that direct visits to a rou
Read the [Instant navigation guide](/docs/app/guides/instant-navigation) for examples and inspection tools. Read the [Instant navigation guide](/docs/app/guides/instant-navigation) for examples and inspection tools.
### Runtime prefetching ### Prefetching
With [Partial Prefetching](/docs/app/api-reference/config/next-config-js/partialPrefetching) enabled, the router prefetches each route's [App Shell](/docs/app/glossary#app-shell) by default, which already includes static content and the session data derived from `cookies()` and `headers()`. Runtime prefetching extends the prefetch with **URL data**: the `searchParams` and dynamic `params` that vary per destination link. With [Partial Prefetching](/docs/app/api-reference/config/next-config-js/partialPrefetching) enabled, the router prefetches each route's [App Shell](/docs/app/glossary#app-shell) by default. The App Shell includes static content and session data derived from `cookies()` and `headers()`. To also prefetch cached content that depends on a link's **URL data**, such as `searchParams` or dynamic `params`, set `prefetch={true}` on that link.
With [`<Link prefetch={true}>`](/docs/app/api-reference/components/link#prefetch) pointing at a [Partial Prefetching](/docs/app/api-reference/config/next-config-js/partialPrefetching) route, Next.js renders that route's component tree again at prefetch time, this time with the destination URL resolved. The same rules apply, but more of the tree resolves now that its `searchParams` and `params` are in scope: With [`<Link prefetch={true}>`](/docs/app/api-reference/components/link#prefetch) pointing at a [Partial Prefetching](/docs/app/api-reference/config/next-config-js/partialPrefetching) route, Next.js renders that route's component tree again at prefetch time, this time with the destination URL resolved. The same rules apply, but more of the tree resolves now that its `searchParams` and `params` are in scope:
- [`use cache`](#usage) called with values extracted from runtime APIs (passed as arguments) joins the runtime prerender - [`use cache`](#usage) called with values extracted from runtime APIs (passed as arguments) joins the per-link prefetch
- [`use cache: private`](/docs/app/api-reference/directives/use-cache-private) executes on the server, reads runtime data directly, and caches the result in the browser, joining the runtime prerender - [`use cache: private`](/docs/app/api-reference/directives/use-cache-private) executes on the server, reads runtime data directly, and caches the result in the browser as part of the per-link prefetch
- [`<Suspense>`](#streaming-uncached-data) fallbacks stay in the runtime prerender while uncached content streams at request time - [`<Suspense>`](#streaming-uncached-data) fallbacks stay in the prefetched UI while uncached content streams at request time
This generates a **runtime prerender** that extends past the static shell with content the destination URL unlocks. Because it happens during the prefetch, the navigation has nothing to wait on. The cost is a server invocation per prefetchable link. This per-link prefetch includes cached content that resolves after the destination URL is known. It costs a server invocation per prefetchable link.
For example, take a search page that reads `searchParams` from the URL: For example, take a search page that reads `searchParams` from the URL:
...@@ -582,7 +582,7 @@ When a [`<Link>`](/docs/app/api-reference/components/link) to `/search?q=shoes` ...@@ -582,7 +582,7 @@ When a [`<Link>`](/docs/app/api-reference/components/link) to `/search?q=shoes`
See [Adopting Partial Prefetching](/docs/app/guides/adopting-partial-prefetching) to understand how `<Link>` prefetching behaves and how to adopt it. See [Adopting Partial Prefetching](/docs/app/guides/adopting-partial-prefetching) to understand how `<Link>` prefetching behaves and how to adopt it.
See the [Runtime prefetching guide](/docs/app/guides/runtime-prefetching) for full patterns and the [`prefetch` reference](/docs/app/api-reference/file-conventions/route-segment-config/prefetch) for all modes. See the [Optimizing prefetching guide](/docs/app/guides/optimizing-prefetching) for full patterns and the [`prefetch` reference](/docs/app/api-reference/file-conventions/route-segment-config/prefetch) for all modes.
## Where cached content is stored ## Where cached content is stored
...@@ -590,7 +590,7 @@ A cached function's output is serialized into an **RSC payload**, at build time ...@@ -590,7 +590,7 @@ A cached function's output is serialized into an **RSC payload**, at build time
- **Prerendered HTML.** The payload is rendered to HTML and stored on disk when self-hosting, or in your platform's durable storage behind a CDN. That HTML is the [static shell](#prerendering) at build time and the concrete page after an [ISR](#incremental-static-regeneration) upgrade, with [`revalidate`](/docs/app/api-reference/functions/cacheLife#revalidate) and [`expire`](/docs/app/api-reference/functions/cacheLife#expire) controlling when it's rebuilt. - **Prerendered HTML.** The payload is rendered to HTML and stored on disk when self-hosting, or in your platform's durable storage behind a CDN. That HTML is the [static shell](#prerendering) at build time and the concrete page after an [ISR](#incremental-static-regeneration) upgrade, with [`revalidate`](/docs/app/api-reference/functions/cacheLife#revalidate) and [`expire`](/docs/app/api-reference/functions/cacheLife#expire) controlling when it's rebuilt.
- **Shared store.** By default the result stays in a per-instance, in-memory store that is ephemeral on serverless. [`use cache: remote`](/docs/app/api-reference/directives/use-cache-remote) moves it to a durable [cache handler](/docs/app/api-reference/config/next-config-js/cacheHandlers) shared across instances, a network roundtrip that pays off only at a **high hit rate**. - **Shared store.** By default the result stays in a per-instance, in-memory store that is ephemeral on serverless. [`use cache: remote`](/docs/app/api-reference/directives/use-cache-remote) moves it to a durable [cache handler](/docs/app/api-reference/config/next-config-js/cacheHandlers) shared across instances, a network roundtrip that pays off only at a **high hit rate**.
- **Browser.** The payload is included in the RSC sent for a client navigation or [prefetch](#runtime-prefetching), where the browser keeps it fresh for its [`stale`](/docs/app/api-reference/functions/cacheLife#stale) window. [`use cache: private`](/docs/app/api-reference/directives/use-cache-private) results live only here. - **Browser.** The payload is included in the RSC sent for a client navigation or [prefetch](#prefetching), where the browser keeps it fresh for its [`stale`](/docs/app/api-reference/functions/cacheLife#stale) window. [`use cache: private`](/docs/app/api-reference/directives/use-cache-private) results live only here.
> **Good to know:** An [App Shell](/docs/app/glossary#app-shell) that reads `cookies()` or `headers()` is session-specific, cached per session on the client rather than in the shared server cache. > **Good to know:** An [App Shell](/docs/app/glossary#app-shell) that reads `cookies()` or `headers()` is session-specific, cached per session on the client rather than in the shared server cache.
......
...@@ -7,14 +7,14 @@ related: ...@@ -7,14 +7,14 @@ related:
description: Learn more about prefetching and instant navigations. description: Learn more about prefetching and instant navigations.
links: links:
- app/guides/instant-navigation - app/guides/instant-navigation
- app/guides/runtime-prefetching - app/guides/optimizing-prefetching
- app/api-reference/config/next-config-js/partialPrefetching - 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/prefetch
--- ---
[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. [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.
To prefetch more than the App Shell, a link can opt into [runtime prefetching](/docs/app/guides/runtime-prefetching) with [`<Link prefetch={true}>`](/docs/app/api-reference/components/link#prefetch). The prefetch then also resolves the per-link runtime data (`params`, `searchParams`, and the full URL) and the cached content behind it. To prefetch more than the App Shell, a link can opt into [per-link prefetching](/docs/app/guides/optimizing-prefetching) with [`<Link prefetch={true}>`](/docs/app/api-reference/components/link#prefetch). The prefetch then also resolves URL-specific content that depends on `params`, `searchParams`, or the full URL.
Along the way, Next.js surfaces [instant navigation](/docs/app/guides/instant-navigation) insights in development, naming the link or route to change. Along the way, Next.js surfaces [instant navigation](/docs/app/guides/instant-navigation) insights in development, naming the link or route to change.
...@@ -65,11 +65,11 @@ After enabling the flag, every `<Link>` prefetches its destination's App Shell, ...@@ -65,11 +65,11 @@ After enabling the flag, every `<Link>` prefetches its destination's App Shell,
## What changes for `<Link>` ## What changes for `<Link>`
| `<Link>` prop | Before (Cache Components default) | After Partial Prefetching | | `<Link>` prop | Before (Cache Components default) | After Partial Prefetching |
| ----------------------------------- | -------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- | | ----------------------------------- | -------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
| `<Link href="/x">` | Prefetched the cached page render. | Loads the shared App Shell for `/x`. | | `<Link href="/x">` | Prefetched the cached page render. | Loads the shared App Shell for `/x`. |
| `<Link href="/x" prefetch>` | Prefetched the cached page render **and** any dynamic content. | Loads the App Shell, plus per-link runtime data through [runtime prefetching](/docs/app/guides/runtime-prefetching) when `/x` reads it. | | `<Link href="/x" prefetch>` | Prefetched the cached page render **and** any dynamic content. | Loads the App Shell, plus URL-specific content through [per-link prefetching](/docs/app/guides/optimizing-prefetching) when `/x` reads it. |
| `<Link href="/x" prefetch={false}>` | Disabled prefetching for this link. | Unchanged. Still disabled. | | `<Link href="/x" prefetch={false}>` | Disabled prefetching for this link. | Unchanged. Still disabled. |
The App Shell is shared across every link to a given route, regardless of dynamic params, so rendering many `<Link>`s to the same destination doesn't multiply the work. The App Shell is shared across every link to a given route, regardless of dynamic params, so rendering many `<Link>`s to the same destination doesn't multiply the work.
...@@ -79,13 +79,13 @@ Each `<Link prefetch={true}>` used to prefetch its destination's dynamic content ...@@ -79,13 +79,13 @@ Each `<Link prefetch={true}>` used to prefetch its destination's dynamic content
> **Good to know**: `cookies()` and `headers()` don't tie a prefetch to a URL. They vary per session, not per link, so the App Shell still carries session content. Only `params` and `searchParams` are [URL data](/docs/app/glossary#url-data), which varies per link and can't be included in the shared App Shell. > **Good to know**: `cookies()` and `headers()` don't tie a prefetch to a URL. They vary per session, not per link, so the App Shell still carries session content. Only `params` and `searchParams` are [URL data](/docs/app/glossary#url-data), which varies per link and can't be included in the shared App Shell.
| Destination | Recommendation | | Destination | Recommendation |
| --------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | | --------------------------------------------------------------------------------- | ------------------------------------------------------------------------- |
| [Fully static, or content already cached](#static-or-cached-content) | Remove the now-redundant `prefetch={true}`. | | [Fully static, or content already cached](#static-or-cached-content) | Remove the now-redundant `prefetch={true}`. |
| [Delivered uncached content you want kept ahead of the click](#uncached-content) | Cache it with `use cache`, then remove `prefetch={true}`. | | [Delivered uncached content you want kept ahead of the click](#uncached-content) | Cache it with `use cache`, then remove `prefetch={true}`. |
| [Delivered content that depends on `cookies()` or `headers()`](#session-content) | Cache the lookup behind the session value, then remove `prefetch={true}`. | | [Delivered content that depends on `cookies()` or `headers()`](#session-content) | Cache the lookup behind the session value, then remove `prefetch={true}`. |
| [Reads URL data, or has cached content that depends on it](#url-data) | Keep `prefetch={true}`, and prefetch the content later with runtime prefetching. | | [Reads URL data, or has cached content that depends on it](#url-data) | Keep `prefetch={true}` to resolve the content ahead of the click. |
| [Delivers real-time content that must stay fresh per request](#real-time-content) | Remove `prefetch={true}` and let the content stream in. | | [Delivers real-time content that must stay fresh per request](#real-time-content) | Remove `prefetch={true}` and let the content stream in. |
### Static or cached content ### Static or cached content
...@@ -148,7 +148,7 @@ export default async function Page() { ...@@ -148,7 +148,7 @@ export default async function Page() {
### Session content ### Session content
Content behind [`cookies()`](/docs/app/api-reference/functions/cookies) or [`headers()`](/docs/app/api-reference/functions/headers) varies per session, not per link, and [session data resolves in the App Shell](/docs/app/guides/runtime-prefetching#session-data-resolves-in-the-shell), so cached session content still gets included. Read the session value outside the cached function and pass it in, then remove `prefetch={true}` from the links: Content behind [`cookies()`](/docs/app/api-reference/functions/cookies) or [`headers()`](/docs/app/api-reference/functions/headers) varies per session, not per link, and [session data resolves in the App Shell](/docs/app/guides/optimizing-prefetching#include-session-data-in-the-shell), so cached session content still gets included. Read the session value outside the cached function and pass it in, then remove `prefetch={true}` from the links:
```tsx filename="app/dashboard/page.tsx" switcher ```tsx filename="app/dashboard/page.tsx" switcher
// Before // Before
...@@ -437,7 +437,7 @@ Everything outside the boundary stays in the shared App Shell, and only the URL- ...@@ -437,7 +437,7 @@ Everything outside the boundary stays in the shared App Shell, and only the URL-
## Prefetching URL data ## Prefetching URL data
Content that depends on [URL data](/docs/app/glossary#url-data) (`params`, `searchParams`) can't be included in the shared App Shell, so it streams in after navigation. [Runtime prefetching](/docs/app/guides/runtime-prefetching) resolves it ahead of the click for links with `prefetch={true}`, at the cost of a server invocation per prefetchable link. To make the content resolvable at prefetch time, cache it behind the read with [`use cache`](/docs/app/api-reference/directives/use-cache). For a search page that reads `searchParams`: Content that depends on [URL data](/docs/app/glossary#url-data) (`params`, `searchParams`) can't be included in the shared App Shell, so it streams in after navigation. [Per-link prefetching](/docs/app/guides/optimizing-prefetching) resolves it ahead of the click for links with `prefetch={true}`, at the cost of a server invocation per prefetchable link. To make the content resolvable at prefetch time, cache it behind the read with [`use cache`](/docs/app/api-reference/directives/use-cache). For a search page that reads `searchParams`:
```tsx filename="app/search/page.tsx" switcher ```tsx filename="app/search/page.tsx" switcher
// Before - the results stream in after navigation // Before - the results stream in after navigation
...@@ -537,4 +537,4 @@ export default function Page({ searchParams }) { ...@@ -537,4 +537,4 @@ export default function Page({ searchParams }) {
} }
``` ```
The [runtime prefetching guide](/docs/app/guides/runtime-prefetching) covers when the cost pays off and the caching patterns behind runtime reads. The [Optimizing prefetching guide](/docs/app/guides/optimizing-prefetching) covers when the cost pays off and the caching patterns behind runtime reads.
...@@ -9,7 +9,7 @@ related: ...@@ -9,7 +9,7 @@ related:
- app/guides/authentication - app/guides/authentication
- app/getting-started/caching - app/getting-started/caching
- app/getting-started/fetching-data - app/getting-started/fetching-data
- app/guides/runtime-prefetching - app/guides/optimizing-prefetching
- app/api-reference/directives/use-cache-private - app/api-reference/directives/use-cache-private
- app/api-reference/functions/cacheTag - app/api-reference/functions/cacheTag
- app/api-reference/config/next-config-js/cacheComponents - app/api-reference/config/next-config-js/cacheComponents
...@@ -296,7 +296,7 @@ Cached reads already have a lifetime, so this mostly happens on its own. A `use ...@@ -296,7 +296,7 @@ Cached reads already have a lifetime, so this mostly happens on its own. A `use
Two things keep it that way: Two things keep it that way:
- If you tune the lifetime with [`cacheLife`](/docs/app/api-reference/functions/cacheLife), keep `stale` at 30 seconds or more. Below that, the scope drops out of prefetching. See [`cacheLife` client cache behavior](/docs/app/api-reference/functions/cacheLife#client-cache-behavior). - If you tune the lifetime with [`cacheLife`](/docs/app/api-reference/functions/cacheLife), keep `stale` at 30 seconds or more. Below that, the scope drops out of prefetching. See [`cacheLife` client cache behavior](/docs/app/api-reference/functions/cacheLife#client-cache-behavior).
- A route that _also_ depends on the URL (a `params` or `searchParams` value) needs [`<Link prefetch={true}>`](/docs/app/api-reference/components/link#prefetch) on the links pointing at it. That opts into [runtime prefetching](/docs/app/guides/runtime-prefetching), which resolves the per-link data ahead of the click. - A route that _also_ depends on the URL (a `params` or `searchParams` value) needs [`<Link prefetch={true}>`](/docs/app/api-reference/components/link#prefetch) on the links pointing at it. That opts into [per-link prefetching](/docs/app/guides/optimizing-prefetching), which resolves the per-link data ahead of the click.
```tsx filename="app/page.tsx" ```tsx filename="app/page.tsx"
<Link href={`/notes/${note.id}`} prefetch={true}> <Link href={`/notes/${note.id}`} prefetch={true}>
...@@ -304,7 +304,7 @@ Two things keep it that way: ...@@ -304,7 +304,7 @@ Two things keep it that way:
</Link> </Link>
``` ```
The destination needs [Partial Prefetching](/docs/app/guides/adopting-partial-prefetching) for this, so enable the [`partialPrefetching`](/docs/app/api-reference/config/next-config-js/partialPrefetching) flag or set `prefetch = 'partial'` on the segment. Add the prop where the wait is worth it: a runtime prefetch costs one server invocation per link, so a sidebar of `/chat/[id]` links pays that cost per item. The destination needs [Partial Prefetching](/docs/app/guides/adopting-partial-prefetching) for this, so enable the [`partialPrefetching`](/docs/app/api-reference/config/next-config-js/partialPrefetching) flag or set `prefetch = 'partial'` on the segment. Add the prop where the wait is worth it: that prefetch costs one server invocation per link, so a sidebar of `/chat/[id]` links pays that cost per item.
## Common pitfalls ## Common pitfalls
......
...@@ -7,7 +7,7 @@ related: ...@@ -7,7 +7,7 @@ related:
description: Explore the full instant API, caching, and revalidation. description: Explore the full instant API, caching, and revalidation.
links: links:
- app/api-reference/file-conventions/route-segment-config/instant - app/api-reference/file-conventions/route-segment-config/instant
- app/guides/runtime-prefetching - app/guides/optimizing-prefetching
- app/getting-started/caching - app/getting-started/caching
- app/getting-started/revalidating - app/getting-started/revalidating
- app/guides/prefetching - app/guides/prefetching
...@@ -36,7 +36,7 @@ This is also why client-side hooks behave differently. `useSearchParams()` suspe ...@@ -36,7 +36,7 @@ This is also why client-side hooks behave differently. `useSearchParams()` suspe
</details> </details>
Runtime prefetching extends the static shell with a link's URL data (`searchParams` and `params`) by invoking the route at prefetch time. Ensuring navigations are instant is the foundation: a route that doesn't navigate instantly without runtime prefetching won't navigate instantly with it either. See [Runtime prefetching](/docs/app/guides/runtime-prefetching) for the patterns. With `prefetch={true}`, per-link prefetching resolves a link's URL data (`searchParams` and `params`) before navigation. First make the route instant with its App Shell. Per-link prefetching cannot fix a route that blocks without it. See [Optimizing prefetching](/docs/app/guides/optimizing-prefetching) for the patterns.
## Quick start ## Quick start
...@@ -78,17 +78,17 @@ The rest of this guide covers the tools these migrations use, walks a navigation ...@@ -78,17 +78,17 @@ The rest of this guide covers the tools these migrations use, walks a navigation
With Cache Components, **caching directives** (`"use cache"` and its variants) assign a lifetime to an async function's result, which is what lets Next.js include it in the static shell. With Cache Components, **caching directives** (`"use cache"` and its variants) assign a lifetime to an async function's result, which is what lets Next.js include it in the static shell.
> **Good to know:** [`"use cache: private"`](/docs/app/api-reference/directives/use-cache-private) is a variant for caching functions that read runtime APIs like `cookies()` and `headers()`. The result is cached in the browser only, not on the server. **It can't be part of the static shell.** See [`"use cache: private"`](/docs/app/guides/runtime-prefetching#use-cache-private) in the runtime prefetching guide for how it pairs with prefetching. > **Good to know:** [`"use cache: private"`](/docs/app/api-reference/directives/use-cache-private) is a variant for caching functions that read runtime APIs like `cookies()` and `headers()`. The result is cached in the browser only, not on the server. **It can't be part of the static shell.** See [`"use cache: private"`](/docs/app/guides/optimizing-prefetching#use-cache-private) in the Optimizing prefetching guide for how it pairs with prefetching.
**`<Suspense>`** declares fallback UI for parts of the tree that read uncached data or runtime APIs like `cookies()` and `headers()`; the content streams into the fallback when it resolves. **`<Suspense>`** declares fallback UI for parts of the tree that read uncached data or runtime APIs like `cookies()` and `headers()`; the content streams into the fallback when it resolves.
> **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. > **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. For a link with `prefetch={true}`, [per-link prefetching](/docs/app/guides/optimizing-prefetching) makes URL data available before navigation, so the fallback can become part of the prefetched 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. [Runtime prefetching](/docs/app/guides/runtime-prefetching) builds on it, resolving a link's URL data on top. Next.js can also generate an [**App Shell**](/docs/app/glossary#app-shell) per route, which renders during client navigations while remaining content streams. Partial Prefetching uses the App Shell as the default `<Link>` prefetch. A link with `prefetch={true}` can also resolve cached content that depends on that link's URL data.
### Tune what `<Link>` prefetches ### Prefetch URL data for a link
Under [Partial Prefetching](/docs/app/guides/adopting-partial-prefetching), each visible `<Link>` prefetches the destination's App Shell by default. The shell is shared across every link to the same route, so rendering a `<Link>` is effectively free. Under [Partial Prefetching](/docs/app/guides/adopting-partial-prefetching), each visible `<Link>` prefetches the destination's App Shell by default. Links to the same route share one App Shell instead of triggering a separate App Shell request for each link.
To prefetch the page content alongside the shell for a specific link, set [`prefetch={true}`](/docs/app/api-reference/components/link#prefetch): To prefetch the page content alongside the shell for a specific link, set [`prefetch={true}`](/docs/app/api-reference/components/link#prefetch):
...@@ -98,7 +98,7 @@ To prefetch the page content alongside the shell for a specific link, set [`pref ...@@ -98,7 +98,7 @@ To prefetch the page content alongside the shell for a specific link, set [`pref
</Link> </Link>
``` ```
With Partial Prefetching enabled, `prefetch={true}` also opts the link into [runtime prefetching](/docs/app/guides/runtime-prefetching), which resolves the per-link URL data (`params`, `searchParams`, the full URL) ahead of the click. With Partial Prefetching enabled, `prefetch={true}` also opts the link into [per-link prefetching](/docs/app/guides/optimizing-prefetching), which resolves the per-link URL data (`params`, `searchParams`, the full URL) ahead of the click.
### Validate instant navigation ### Validate instant navigation
...@@ -332,7 +332,7 @@ bun add -D @next/playwright @playwright/test ...@@ -332,7 +332,7 @@ bun add -D @next/playwright @playwright/test
A route can be reached two ways, and a `<Suspense>` boundary can cover one without covering the other: A route can be reached two ways, and a `<Suspense>` boundary can cover one without covering the other:
- **Initial page load**: Use `page.goto()` to test the static UI from the document response. - **Initial page load**: Use `page.goto()` to test the static UI from the document response.
- **Client navigation**: Click a `<Link>` to test the destination's prefetched UI. [Runtime prefetching](/docs/app/guides/runtime-prefetching) can add request-specific content to this UI. - **Client navigation**: Click a `<Link>` to test the destination's prefetched UI. [Per-link prefetching](/docs/app/guides/optimizing-prefetching) can add request-specific content to this UI.
```typescript filename="e2e/navigation.test.ts" highlight={6-14,20-25} ```typescript filename="e2e/navigation.test.ts" highlight={6-14,20-25}
import { test, expect } from '@playwright/test' import { test, expect } from '@playwright/test'
...@@ -539,7 +539,7 @@ Agents working on a Cache Components route typically reach for three levers: ...@@ -539,7 +539,7 @@ Agents working on a Cache Components route typically reach for three levers:
- **Push down**: extract I/O into a Suspense-wrapped child so the parent stays static and static siblings lift into the shell. - **Push down**: extract I/O into a Suspense-wrapped child so the parent stays static and static siblings lift into the shell.
- **Cache**: pair `'use cache'` with [`cacheLife`](/docs/app/api-reference/functions/cacheLife) to assign a freshness profile. - **Cache**: pair `'use cache'` with [`cacheLife`](/docs/app/api-reference/functions/cacheLife) to assign a freshness profile.
- **Runtime prefetching** (nav-only): when a route reads URL data (`searchParams` or `params`), opt it into [runtime prefetching](/docs/app/guides/runtime-prefetching) so the framework resolves that data at link-prefetch time. Session data from `cookies()` or `headers()` already lands in the App Shell without it. - **Per-link prefetching** (nav-only): when a route reads URL data (`searchParams` or `params`), opt it into [per-link prefetching](/docs/app/guides/optimizing-prefetching) so the framework resolves that data at link-prefetch time. Session data from `cookies()` or `headers()` already lands in the App Shell without it.
Each refactor should pair with a before/after capture to verify the change actually landed. Identical-looking captures mean the refactor didn't take effect. Each refactor should pair with a before/after capture to verify the change actually landed. Identical-looking captures mean the refactor didn't take effect.
...@@ -579,6 +579,6 @@ For opted-out segments, the navigation blocks on the server. If the content depe ...@@ -579,6 +579,6 @@ For opted-out segments, the navigation blocks on the server. If the content depe
- [Adopting Partial Prefetching](/docs/app/guides/adopting-partial-prefetching) for the recommended `<Link>` defaults and the migration path off `unstable_eager` - [Adopting Partial Prefetching](/docs/app/guides/adopting-partial-prefetching) for the recommended `<Link>` defaults and the migration path off `unstable_eager`
- [`instant` API reference](/docs/app/api-reference/file-conventions/route-segment-config/instant) for the full configuration - [`instant` API reference](/docs/app/api-reference/file-conventions/route-segment-config/instant) for the full configuration
- [Runtime prefetching](/docs/app/guides/runtime-prefetching) when parts of your route depend on URL data (`searchParams` or `params`) and you want it in the shell - [Optimizing prefetching](/docs/app/guides/optimizing-prefetching) when parts of your route depend on URL data (`searchParams` or `params`) and should resolve before navigation
- [Caching](/docs/app/getting-started/caching) for background on `use cache`, Suspense, and Partial Prerendering - [Caching](/docs/app/getting-started/caching) for background on `use cache`, Suspense, and Partial Prerendering
- [Revalidating](/docs/app/getting-started/revalidating) for how to expire cached data with `cacheLife` and `updateTag` - [Revalidating](/docs/app/getting-started/revalidating) for how to expire cached data with `cacheLife` and `updateTag`
...@@ -738,7 +738,7 @@ In this demo, the comment thread stays dynamic because readers expect the curren ...@@ -738,7 +738,7 @@ In this demo, the comment thread stays dynamic because readers expect the curren
#### Prefetch the destination with the real request #### Prefetch the destination with the real request
Under [Partial Prefetching](/docs/app/guides/adopting-partial-prefetching) (Next.js 16.3 and later), `<Link>` prefetches the destination's [App Shell](/docs/app/glossary#app-shell): the route output that is shared across links for the current user. The shell does not include [URL data](/docs/app/glossary#url-data), because `params` and `searchParams` are link-specific. Opt the link into [runtime prefetching](/docs/app/guides/runtime-prefetching) with `prefetch={true}` to resolve that URL data ahead of the click: Under [Partial Prefetching](/docs/app/guides/adopting-partial-prefetching) (Next.js 16.3 and later), `<Link>` prefetches the destination's [App Shell](/docs/app/glossary#app-shell): the route output that is shared across links for the current user. The shell does not include [URL data](/docs/app/glossary#url-data), because `params` and `searchParams` are link-specific. Opt the link into [per-link prefetching](/docs/app/guides/optimizing-prefetching) with `prefetch={true}` to resolve that URL data ahead of the click:
```tsx filename="features/task/components/task-card.tsx" ```tsx filename="features/task/components/task-card.tsx"
<Link href={`/task/${id}`} prefetch={true}> <Link href={`/task/${id}`} prefetch={true}>
...@@ -746,7 +746,7 @@ Under [Partial Prefetching](/docs/app/guides/adopting-partial-prefetching) (Next ...@@ -746,7 +746,7 @@ Under [Partial Prefetching](/docs/app/guides/adopting-partial-prefetching) (Next
</Link> </Link>
``` ```
Runtime prefetching is most valuable when the destination has URL-specific work that users are likely to need next. Cached reads make the prefetched output reusable and tag-invalidatable in the [Client Cache](/docs/app/glossary#client-cache); dynamic reads can still resolve before the click, but each prefetch can do real server work. In the companion app, the task cards prefetch the detail page as they scroll into view, so it paints instantly by the time the user clicks. Per-link prefetching is most valuable when the destination has URL-specific work that users are likely to need next. Cached reads make the prefetched output reusable and tag-invalidatable in the [Client Cache](/docs/app/glossary#client-cache); dynamic reads can still resolve before the click, but each prefetch can do real server work. In the companion app, the task cards prefetch the detail page as they scroll into view, so it paints instantly by the time the user clicks.
## Next steps ## Next steps
...@@ -760,7 +760,7 @@ The patterns in this guide combine a handful of primitives: ...@@ -760,7 +760,7 @@ The patterns in this guide combine a handful of primitives:
| A form needs pending, reset, and result state | [`useActionState`](https://react.dev/reference/react/useActionState) | | A form needs pending, reset, and result state | [`useActionState`](https://react.dev/reference/react/useActionState) |
| An ancestor should show pending state for work happening elsewhere | [`data-pending`](https://react.dev/reference/react-dom/components/form#props) attribute styled with CSS | | An ancestor should show pending state for work happening elsewhere | [`data-pending`](https://react.dev/reference/react-dom/components/form#props) attribute styled with CSS |
| Reusable reads should survive across requests and stay fresh after writes | [`'use cache'`](/docs/app/api-reference/directives/use-cache) with [`cacheTag`](/docs/app/api-reference/functions/cacheTag), revalidated by [`updateTag`](/docs/app/api-reference/functions/updateTag) or [`revalidateTag`](/docs/app/api-reference/functions/revalidateTag) | | Reusable reads should survive across requests and stay fresh after writes | [`'use cache'`](/docs/app/api-reference/directives/use-cache) with [`cacheTag`](/docs/app/api-reference/functions/cacheTag), revalidated by [`updateTag`](/docs/app/api-reference/functions/updateTag) or [`revalidateTag`](/docs/app/api-reference/functions/revalidateTag) |
| Navigation between pages of an interactive app should feel instant | [`<Link>`](/docs/app/api-reference/components/link) prefetching with [Partial Prefetching](/docs/app/guides/adopting-partial-prefetching), and [Runtime prefetching](/docs/app/guides/runtime-prefetching) via `prefetch={true}` for content that depends on URL data | | Navigation between pages of an interactive app should feel instant | [`<Link>`](/docs/app/api-reference/components/link) prefetching with [Partial Prefetching](/docs/app/guides/adopting-partial-prefetching), and [per-link prefetching](/docs/app/guides/optimizing-prefetching) via `prefetch={true}` for content that depends on URL data |
Most patterns mix two or more of these. Reach for whichever primitive fits the constraint you're solving. Most patterns mix two or more of these. Reach for whichever primitive fits the constraint you're solving.
......
...@@ -307,7 +307,7 @@ For most apps, the pending loading state is enough. Add a banner in the root lay ...@@ -307,7 +307,7 @@ For most apps, the pending loading state is enough. Add a banner in the root lay
The same pattern extends to parameterized routes. A route like `/chats/[id]` renders its shared [App Shell](/docs/app/glossary#app-shell) when you navigate to `/chats/42` offline, and the dynamic messages behind its `<Suspense>` boundary load when the connection returns. The same pattern extends to parameterized routes. A route like `/chats/[id]` renders its shared [App Shell](/docs/app/glossary#app-shell) when you navigate to `/chats/42` offline, and the dynamic messages behind its `<Suspense>` boundary load when the connection returns.
If the route also prefetches its per-link URL data ahead of the click, `/chats/42` renders its messages from that prefetch immediately, even offline, instead of waiting for the connection to return. See [runtime prefetching](/docs/app/guides/runtime-prefetching) to learn more. If the route also prefetches its per-link URL data ahead of the click, `/chats/42` renders its messages from that prefetch immediately, even offline, instead of waiting for the connection to return. See [Optimizing prefetching](/docs/app/guides/optimizing-prefetching) to learn more.
## Retry Server Actions after the network returns ## Retry Server Actions after the network returns
......
...@@ -85,10 +85,10 @@ Next.js stores prefetched React Server Component payloads in memory, keyed by ro ...@@ -85,10 +85,10 @@ Next.js stores prefetched React Server Component payloads in memory, keyed by ro
With [Partial Prefetching](/docs/app/glossary#partial-prefetching) enabled via the [`partialPrefetching`](/docs/app/api-reference/config/next-config-js/partialPrefetching) config (which requires [Cache Components](/docs/app/getting-started/caching)), prefetching switches from the all-or-nothing model above to a per-route [App Shell](/docs/app/glossary#app-shell): With [Partial Prefetching](/docs/app/glossary#partial-prefetching) enabled via the [`partialPrefetching`](/docs/app/api-reference/config/next-config-js/partialPrefetching) config (which requires [Cache Components](/docs/app/getting-started/caching)), prefetching switches from the all-or-nothing model above to a per-route [App Shell](/docs/app/glossary#app-shell):
- **One shell per route, shared across links.** `<Link>` prefetches the route's App Shell, which holds its static and session output. Any number of links to the same route reuse that one shell, fetched once as the first link enters the viewport, so a page with many links makes fewer prefetch requests than prefetching each route in full. - **One shell per route, shared across links.** `<Link>` prefetches the route's App Shell, which holds its static and session output. Any number of links to the same route reuse that one shell, fetched once as the first link enters the viewport, so a page with many links makes fewer prefetch requests than prefetching each route in full.
- **The rest streams in.** Uncached data streams in after navigation, behind the shell's `<Suspense>` boundaries. A link can also resolve its URL data (`searchParams`, `params`) at prefetch time with [`prefetch={true}`](/docs/app/guides/runtime-prefetching). - **The rest streams in.** Uncached data streams in after navigation, behind the shell's `<Suspense>` boundaries. A link can also resolve its URL data (`searchParams`, `params`) at prefetch time with [`prefetch={true}`](/docs/app/guides/optimizing-prefetching).
- **Invalidations refresh prefetches.** Data invalidations (`revalidateTag`, `revalidatePath`) silently refresh associated prefetches. - **Invalidations refresh prefetches.** Data invalidations (`revalidateTag`, `revalidatePath`) silently refresh associated prefetches.
See [Adopting Partial Prefetching](/docs/app/guides/adopting-partial-prefetching) for the behavior change and the recommended adoption path. See [Adopting Partial Prefetching](/docs/app/guides/adopting-partial-prefetching) for the behavior change and the recommended adoption path. See [Optimizing prefetching](/docs/app/guides/optimizing-prefetching) to resolve cached URL-specific content before navigation with `prefetch={true}`.
## Controlling prefetching ## Controlling prefetching
......
...@@ -151,7 +151,7 @@ async function getRecommendations(productId) { ...@@ -151,7 +151,7 @@ async function getRecommendations(productId) {
} }
``` ```
> **Good to know**: The `stale` time must be at least 30 seconds for runtime prefetching to work, and at least 5 minutes for the content to be included in the route's [App Shell](/docs/app/glossary#app-shell). See [`cacheLife` prerendering behavior](/docs/app/api-reference/functions/cacheLife#prerendering-behavior) for details. > **Good to know**: The `stale` time must be at least 30 seconds for per-link prefetching to work, and at least 5 minutes for the content to be included in the route's [App Shell](/docs/app/glossary#app-shell). See [`cacheLife` prerendering behavior](/docs/app/api-reference/functions/cacheLife#prerendering-behavior) for details.
## Request APIs allowed in private caches ## Request APIs allowed in private caches
......
...@@ -300,7 +300,7 @@ Prefetching happens when a `<Link />` component enters the user's viewport (init ...@@ -300,7 +300,7 @@ Prefetching happens when a `<Link />` component enters the user's viewport (init
The following values can be passed to the `prefetch` prop: The following values can be passed to the `prefetch` prop:
- **`"auto"` or `null` (default)**: Prefetch behavior depends on whether the route is static or dynamic. For static routes, the full route will be prefetched (including all its data). For dynamic routes, the partial route down to the nearest segment with a [`loading.js`](/docs/app/api-reference/file-conventions/loading#instant-loading-states) boundary will be prefetched. - **`"auto"` or `null` (default)**: Prefetch behavior depends on whether the route is static or dynamic. For static routes, the full route will be prefetched (including all its data). For dynamic routes, the partial route down to the nearest segment with a [`loading.js`](/docs/app/api-reference/file-conventions/loading#instant-loading-states) boundary will be prefetched.
- **`true`**: The full route is prefetched for both static and dynamic routes. With [Partial Prefetching](/docs/app/guides/adopting-partial-prefetching) enabled, the prefetch is the [App Shell](/docs/app/glossary#app-shell) plus the per-link runtime data and the cached content behind it. See [Runtime prefetching](/docs/app/guides/runtime-prefetching). - **`true`**: The full route is prefetched for both static and dynamic routes. With [Partial Prefetching](/docs/app/guides/adopting-partial-prefetching) enabled, the prefetch includes the [App Shell](/docs/app/glossary#app-shell) and cached content that depends on the link's URL data. See [Optimizing prefetching](/docs/app/guides/optimizing-prefetching).
- `false`: Prefetching will never happen both on entering the viewport and on hover. - `false`: Prefetching will never happen both on entering the viewport and on hover.
> **With Partial Prefetching enabled** ([`partialPrefetching: true`](/docs/app/api-reference/config/next-config-js/partialPrefetching)): the default changes. `auto` prefetches the per-route [App Shell](/docs/app/glossary#app-shell) (the route's static and cached content) instead of the full page. See [Adopting Partial Prefetching](/docs/app/guides/adopting-partial-prefetching) for the full behavior change. > **With Partial Prefetching enabled** ([`partialPrefetching: true`](/docs/app/api-reference/config/next-config-js/partialPrefetching)): the default changes. `auto` prefetches the per-route [App Shell](/docs/app/glossary#app-shell) (the route's static and cached content) instead of the full page. See [Adopting Partial Prefetching](/docs/app/guides/adopting-partial-prefetching) for the full behavior change.
......
...@@ -39,11 +39,11 @@ export default function Page() { ...@@ -39,11 +39,11 @@ export default function Page() {
Opts the segment into [Partial Prefetching](/docs/app/guides/adopting-partial-prefetching) without enabling the global [`partialPrefetching`](/docs/app/api-reference/config/next-config-js/partialPrefetching) flag. A `<Link>` pointing at a segment with `prefetch = 'partial'` loads the per-route [App Shell](/docs/app/glossary#app-shell) instead of the legacy full prefetch. Set this on the destination, not the link. Opts the segment into [Partial Prefetching](/docs/app/guides/adopting-partial-prefetching) without enabling the global [`partialPrefetching`](/docs/app/api-reference/config/next-config-js/partialPrefetching) flag. A `<Link>` pointing at a segment with `prefetch = 'partial'` loads the per-route [App Shell](/docs/app/glossary#app-shell) instead of the legacy full prefetch. Set this on the destination, not the link.
For links that opt into a wider prefetch with [`<Link prefetch={true}>`](/docs/app/api-reference/components/link#prefetch), Next.js may also prefetch the segment at runtime. The server renders a fresh response that resolves per-link runtime data (`params`, `searchParams`, and the full URL). On pages where all the content is statically renderable, Next.js serves prefetches from the static cache. If a page accesses non-static data, it's prefetched at runtime. For links that opt into a wider prefetch with [`<Link prefetch={true}>`](/docs/app/api-reference/components/link#prefetch), Next.js uses per-link prefetching. The server renders a fresh response that resolves URL data (`params`, `searchParams`, and the full URL). On pages where all the content is statically renderable, Next.js serves prefetches from the static cache. If a page accesses non-static data, it's prefetched at runtime.
Use this for incremental adoption when you can't enable `partialPrefetching` for the entire app at once. Once every route in scope has `prefetch = 'partial'`, enable the global flag and remove the per-route exports. Use this for incremental adoption when you can't enable `partialPrefetching` for the entire app at once. Once every route in scope has `prefetch = 'partial'`, enable the global flag and remove the per-route exports.
> **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. > **Good to know**: When Next.js performs a per-link prefetch for a segment, all downstream segments are included in the same request. Segments deeper in the tree that are configured with `'force-disabled'` will still be prefetched as part of the response.
```tsx filename="page.tsx" ```tsx filename="page.tsx"
export const prefetch = 'partial' export const prefetch = 'partial'
...@@ -61,7 +61,7 @@ A prefetch starts with a `<Link>` that expresses intent (should this destination ...@@ -61,7 +61,7 @@ A prefetch starts with a `<Link>` that expresses intent (should this destination
A destination can't know which links target it, so the segment config caps what any `<Link prefetch={true}>` pulls: A destination can't know which links target it, so the segment config caps what any `<Link prefetch={true}>` pulls:
- [`'partial'`](#partial): App Shell for default links; a `<Link prefetch={true}>` additionally resolves per-link runtime data (`params`, `searchParams`, the full URL). - [`'partial'`](#partial): App Shell for default links; a `<Link prefetch={true}>` additionally resolves URL data (`params`, `searchParams`, and the full URL) and the cached content behind it.
- [`'force-disabled'`](#force-disabled): skip segment data entirely. - [`'force-disabled'`](#force-disabled): skip segment data entirely.
`<Link prefetch={false}>` skips prefetching at the link level regardless of how the destination is configured. `<Link prefetch={false}>` skips prefetching at the link level regardless of how the destination is configured.
......
...@@ -8,10 +8,10 @@ related: ...@@ -8,10 +8,10 @@ related:
- app/api-reference/config/next-config-js/cacheComponents - app/api-reference/config/next-config-js/cacheComponents
- app/api-reference/file-conventions/route-segment-config/prefetch - app/api-reference/file-conventions/route-segment-config/prefetch
- app/api-reference/components/link - app/api-reference/components/link
- app/guides/runtime-prefetching - app/guides/optimizing-prefetching
--- ---
`partialPrefetching` enables Partial Prefetching at the app level. The framework prefetches the static parts of each route by default; opt individual routes into [runtime prefetching](/docs/app/guides/runtime-prefetching) to fetch more. `partialPrefetching` enables Partial Prefetching at the app level. The framework prefetches the static parts of each route by default; set `prefetch={true}` on individual links to use [per-link prefetching](/docs/app/guides/optimizing-prefetching) and fetch more.
## Usage ## Usage
...@@ -46,13 +46,13 @@ module.exports = { ...@@ -46,13 +46,13 @@ module.exports = {
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. 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.
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. With `partialPrefetching: true`, Next.js prefetches one reusable [App Shell](/docs/app/glossary#app-shell) per route instead. The App Shell contains rendered output that does not depend on a link's URL. URL-specific content, including content that depends on `params` or `searchParams`, resolves after navigation by default. App Shells are cached on the client, so links to the same route reuse one prefetch.
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. 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 caches the shell per session on the client. > **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). The prefetch also resolves per-link runtime data like `params`, `searchParams`, and the full URL. See [Runtime prefetching](/docs/app/guides/runtime-prefetching). A link can ask for more than the App Shell with [`<Link prefetch={true}>`](/docs/app/api-reference/components/link#prefetch). The prefetch also resolves URL data like `params`, `searchParams`, and the full URL, and the cached content behind it. See [Optimizing prefetching](/docs/app/guides/optimizing-prefetching).
> **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. > **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.
......
...@@ -12,7 +12,7 @@ The Next.js router introduced in version 13, built on top of React Server Compon ...@@ -12,7 +12,7 @@ The Next.js router introduced in version 13, built on top of React Server Compon
## App Shell ## App Shell
A per-route prerender containing the parts of a page that don't depend on URL data. Cached content is included when its [`stale`](/docs/app/api-reference/functions/cacheLife#stale) time is at least 5 minutes, since the shell is reused for longer than shorter-lived content stays fresh. 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). A per-route prerender containing the parts of a page that don't depend on URL data. Cached content is included when its [`stale`](/docs/app/api-reference/functions/cacheLife#stale) time is at least 5 minutes, since the shell is reused for longer than shorter-lived content stays fresh. Routes that read `cookies()` or `headers()` produce one that also includes session data, cached per session on the client. Used as the default prefetch payload during client navigations, the loading state when a [per-link prefetch](/docs/app/guides/optimizing-prefetching) is not ready, and the fallback for [ISR with Cache Components](/docs/app/guides/incremental-static-regeneration-cache-components).
# B # B
......
...@@ -24,7 +24,7 @@ kind: insight ...@@ -24,7 +24,7 @@ kind: insight
During a [client-side navigation](/docs/app/glossary#client-side-navigation), a [`<Link prefetch={true}>`](/docs/app/api-reference/components/link) navigated to a route that has not enabled [Partial Prefetching](/docs/app/glossary#partial-prefetching). With [Cache Components](/docs/app/api-reference/config/next-config-js/cacheComponents) enabled, `prefetch={true}` is a legacy "full" prefetch that pulls down the route's dynamic data along with its [App Shell](/docs/app/glossary#app-shell). This will lead to slower, more expensive prefetches. During a [client-side navigation](/docs/app/glossary#client-side-navigation), a [`<Link prefetch={true}>`](/docs/app/api-reference/components/link) navigated to a route that has not enabled [Partial Prefetching](/docs/app/glossary#partial-prefetching). With [Cache Components](/docs/app/api-reference/config/next-config-js/cacheComponents) enabled, `prefetch={true}` is a legacy "full" prefetch that pulls down the route's dynamic data along with its [App Shell](/docs/app/glossary#app-shell). This will lead to slower, more expensive prefetches.
Routes that opt into Partial Prefetching skip the dynamic data at prefetch time, leaving you free to choose when it loads: at navigation via [streaming](/docs/app/glossary#streaming), ahead of time via [runtime prefetching](/docs/app/guides/runtime-prefetching), or not at all. The check fires at navigation time, not prefetch time, so existing apps that have recently enabled Cache Components are not flooded with warnings for every `<Link prefetch={true}>` on the page. Routes that opt into Partial Prefetching skip the dynamic data at prefetch time, leaving you free to choose when it loads: at navigation via [streaming](/docs/app/glossary#streaming), ahead of time via [per-link prefetching](/docs/app/guides/optimizing-prefetching), or not at all. The check fires at navigation time, not prefetch time, so existing apps that have recently enabled Cache Components are not flooded with warnings for every `<Link prefetch={true}>` on the page.
## Ways to fix this ## Ways to fix this
...@@ -61,7 +61,7 @@ Routes that opt into Partial Prefetching skip the dynamic data at prefetch time, ...@@ -61,7 +61,7 @@ Routes that opt into Partial Prefetching skip the dynamic data at prefetch time,
## Opt into Partial Prefetching ## Opt into Partial Prefetching
Choose this fix when the target route has an [App Shell](/docs/app/glossary#app-shell) with dynamic content below it. Opting into Partial Prefetching tells Next.js to prefetch only the App Shell and defer the dynamic data to navigation. Opt in per-route or app-wide, and from there layer on further prefetch optimizations. Choose this fix when the target route has an [App Shell](/docs/app/glossary#app-shell) with dynamic content below it. Opting into Partial Prefetching tells Next.js to prefetch only the App Shell and defer the dynamic data to navigation. After opting in per route or app-wide, decide whether selected links should also prefetch URL-specific content.
### Patterns ### Patterns
...@@ -92,7 +92,7 @@ module.exports = { ...@@ -92,7 +92,7 @@ module.exports = {
`'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'` 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.
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. 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 per-link runtime data (`params`, `searchParams`), it can't be included in the shared App Shell. With Partial Prefetching enabled, `prefetch={true}` opts the link into [runtime prefetching](/docs/app/guides/runtime-prefetching), so the cached content is prefetched behind the runtime read. 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.
```jsx filename="app/dashboard/page.js" ```jsx filename="app/dashboard/page.js"
import { Suspense } from 'react' import { Suspense } from 'react'
......
...@@ -4,7 +4,7 @@ title: Cannot access `crypto.getRandomValue()`, `crypto.randomUUID()`, or anothe ...@@ -4,7 +4,7 @@ title: Cannot access `crypto.getRandomValue()`, `crypto.randomUUID()`, or anothe
## Why This Error Occurred ## Why This Error Occurred
An API that produces a random value synchronously from the Web Crypto API or from Node's `crypto` package was used in a Server Component before accessing other uncached data through APIs like `fetch()` and native database drivers, or the `connection()` API. While typically random crypto values can be guarded behind Runtime data like `cookies()`, `headers()`, `params`, and `searchParams`, this particular route is configured for Runtime Prefetching which makes these APIs available as part of the prefetch request. Accessing random values synchronously without preceding it with uncached data or `await connection()` interferes with the framework's ability to produce a correct prefetch result. An API that produces a random value synchronously from the Web Crypto API or from Node's `crypto` package was used in a Server Component before accessing other uncached data through APIs like `fetch()` and native database drivers, or the `connection()` API. While typically random crypto values can be guarded behind Runtime data like `cookies()`, `headers()`, `params`, and `searchParams`, this particular route is configured for per-link prefetching, which makes these APIs available as part of the prefetch request. Accessing random values synchronously without preceding it with uncached data or `await connection()` interferes with the framework's ability to produce a correct prefetch result.
## Possible Ways to Fix It ## Possible Ways to Fix It
......
...@@ -4,7 +4,7 @@ title: Cannot access `Date.now()`, `Date()`, or `new Date()` before other uncach ...@@ -4,7 +4,7 @@ title: Cannot access `Date.now()`, `Date()`, or `new Date()` before other uncach
## Why This Error Occurred ## Why This Error Occurred
`Date.now()`, `Date()`, or `new Date()` was used in a Server Component before accessing other uncached data through APIs like `fetch()` and native database drivers, or the `connection()` API. While typically reading the current time can be guarded behind Runtime data like `cookies()`, `headers()`, `params`, and `searchParams`, this particular route is configured for Runtime Prefetching which makes these APIs available as part of the prefetch request. Reading the current time without preceding it with uncached data or `await connection()` interferes with the framework's ability to produce a correct prefetch result. `Date.now()`, `Date()`, or `new Date()` was used in a Server Component before accessing other uncached data through APIs like `fetch()` and native database drivers, or the `connection()` API. While typically reading the current time can be guarded behind Runtime data like `cookies()`, `headers()`, `params`, and `searchParams`, this particular route is configured for per-link prefetching, which makes these APIs available as part of the prefetch request. Reading the current time without preceding it with uncached data or `await connection()` interferes with the framework's ability to produce a correct prefetch result.
## Possible Ways to Fix It ## Possible Ways to Fix It
......
...@@ -4,7 +4,7 @@ title: Cannot access `Math.random()` before other uncached data or `connection() ...@@ -4,7 +4,7 @@ title: Cannot access `Math.random()` before other uncached data or `connection()
## Why This Error Occurred ## Why This Error Occurred
`Math.random()` was called in a Server Component before accessing other uncached data through APIs like `fetch()` and native database drivers, or the `connection()` API. While typically random values can be guarded behind Runtime data like `cookies()`, `headers()`, `params`, and `searchParams`, this particular route is configured for Runtime Prefetching which makes these APIs available as part of the prefetch request. Accessing random values without preceding it with uncached data or `await connection()` interferes with the framework's ability to produce a correct prefetch result. `Math.random()` was called in a Server Component before accessing other uncached data through APIs like `fetch()` and native database drivers, or the `connection()` API. While typically random values can be guarded behind Runtime data like `cookies()`, `headers()`, `params`, and `searchParams`, this particular route is configured for per-link prefetching, which makes these APIs available as part of the prefetch request. Accessing random values without preceding it with uncached data or `await connection()` interferes with the framework's ability to produce a correct prefetch result.
## Possible Ways to Fix It ## Possible Ways to Fix It
......
---
title: '`prefetch={true}` is deprecated (Pages Router)'
---
## Why This Error Occurred
This message is about the Pages Router [`<Link>`](/docs/pages/api-reference/components/link) component from `next/link`.
Since [Next.js 9](/blog/next-9#prefetching-in-viewport-links), the Pages Router `<Link>` prefetches automatically: as a link enters the viewport, Next.js prefetches the route's assets in the background. Passing `prefetch={true}` asks for behavior that is already the default, so the prop is redundant and deprecated.
Prefetch requests are low priority and yield to `fetch()` and XHR requests. Next.js also skips them when the visitor has data-saver enabled.
## Possible Ways to Fix It
Remove the redundant `prefetch` prop, since automatic prefetching is already the default:
```jsx
// Before
<Link href="/about" prefetch={true}>
About
</Link>
// After
<Link href="/about">About</Link>
```
To turn prefetching off for a specific link, set `prefetch={false}`:
```jsx
<Link href="/about" prefetch={false}>
About
</Link>
```
---
title: '`prefetch={true}` is deprecated'
---
## Why This Error Occurred
In [Nextjs 9](/blog/next-9#prefetching-in-viewport-links), the behavior of the `<Link prefetch>` attribute was changed from opt in to opt out. This means that the `<Link prefetch={true}>` is **no longer required**.
`<Link>` will automatically prefetch pages in the background as they appear in the view. If certain pages are rarely visited you can manually set prefetch to false, here's how:
This feature improves the responsiveness of your application by making navigations to new pages quicker.
Next.js uses an Intersection Observer to prefetch the assets necessary in the background.
These requests have low-priority and yield to `fetch()` or XHR requests. Next.js will avoid automatically prefetching if the user has data-saver enabled.
## Possible Ways to Fix It
`<Link prefetch={true}>` is now the default behavior and setting it is no longer required. You can safely remove the `prefetch` attribute.
You can opt out of prefetching using `<Link prefetch={false}>`.
...@@ -106,8 +106,8 @@ hear those words. ...@@ -106,8 +106,8 @@ hear those words.
transcript of the loop. transcript of the loop.
- **Only surface a question for a genuine fork:** a fix that would change - **Only surface a question for a genuine fork:** a fix that would change
behavior, a security-sensitive read, or a route that's dynamic by design (a behavior, a security-sensitive read, or a route that's dynamic by design (a
runtime-prefetch candidate, not a shell to grow). A clean instant fix is not a per-link-prefetch candidate, not a shell to grow). A clean instant fix is not
fork — keep going. With no one to ask (an unattended run), don't block: take a fork — keep going. With no one to ask (an unattended run), don't block: take
the safe default and note the assumption — for a cache-freshness choice, the safe default and note the assumption — for a cache-freshness choice,
defer the read behind `<Suspense>` (always fresh, still instant) rather than defer the read behind `<Suspense>` (always fresh, still instant) rather than
guess a `cacheLife`. guess a `cacheLife`.
...@@ -369,10 +369,10 @@ this gate is as machine-checkable as the others. Detail: ...@@ -369,10 +369,10 @@ this gate is as machine-checkable as the others. Detail:
**When URL data can't be pushed down** (for example, the whole page depends on **When URL data can't be pushed down** (for example, the whole page depends on
`params`, `searchParams`, or the full URL), there may be no meaningful static `params`, `searchParams`, or the full URL), there may be no meaningful static
shell to grow. Don't force one. Runtime prefetching can make the soft shell to grow. Don't force one. Per-link prefetching can make the soft
navigation instant, but it is outside this optimizer loop: it requires Partial navigation instant, but it is outside this optimizer loop: it requires Partial
Prefetching, a `<Link prefetch={true}>`, and cached URL-dependent content. See Prefetching, a `<Link prefetch={true}>`, and cached URL-dependent content. See
[Runtime Prefetching](https://nextjs.org/docs/app/guides/runtime-prefetching) [Optimizing prefetching](https://nextjs.org/docs/app/guides/optimizing-prefetching)
and pattern 10 in `reference/patterns.md` for the requirements, cost trade-offs, and pattern 10 in `reference/patterns.md` for the requirements, cost trade-offs,
manual prefetch caveat, and `instant()` test gotchas. manual prefetch caveat, and `instant()` test gotchas.
...@@ -473,5 +473,5 @@ during an incremental rollout and keep checking any other target routes. ...@@ -473,5 +473,5 @@ during an incremental rollout and keep checking any other target routes.
That skill moves the app onto the better prefetching model: shared App Shell That skill moves the app onto the better prefetching model: shared App Shell
prefetches by default, fewer duplicated full-prefetch requests for visible prefetches by default, fewer duplicated full-prefetch requests for visible
links, a link audit for existing `<Link prefetch={true}>` usage, and optional links, a link audit for existing `<Link prefetch={true}>` usage, and optional
per-link runtime prefetching only where URL-specific content is worth the per-link prefetching only where URL-specific content is worth the
extra server work. extra server work.
...@@ -323,9 +323,9 @@ Prefer per-component boundaries inside the page (patterns #1–#5) over one big ...@@ -323,9 +323,9 @@ Prefer per-component boundaries inside the page (patterns #1–#5) over one big
Patterns 1–9 grow a **static shell** by moving dynamic reads behind boundaries. Session data from `cookies()` and `headers()` is handled by the earlier patterns. URL data is different: `params`, `searchParams`, and the full URL belong to one link, while the App Shell is shared by every link to the route. Patterns 1–9 grow a **static shell** by moving dynamic reads behind boundaries. Session data from `cookies()` and `headers()` is handled by the earlier patterns. URL data is different: `params`, `searchParams`, and the full URL belong to one link, while the App Shell is shared by every link to the route.
If the whole route depends on URL data, pushing the read lower may leave no meaningful shared shell to commit. That is the optimizer's stop point, not another shell refactor. Return to `SKILL.md` after the optimization loop for the optional runtime-prefetch follow-up. If the whole route depends on URL data, pushing the read lower may leave no meaningful shared shell to commit. That is the optimizer's stop point, not another shell refactor. Return to `SKILL.md` after the optimization loop for the optional per-link-prefetch follow-up.
Runtime prefetching is the only way for this soft navigation to commit the Per-link prefetching is the only way for this soft navigation to commit the
URL-specific content before the click. It has **three requirements**: URL-specific content before the click. It has **three requirements**:
```tsx ```tsx
...@@ -347,11 +347,11 @@ Under `instant()` the runtime entry is what commits, so the real content, not a ...@@ -347,11 +347,11 @@ Under `instant()` the runtime entry is what commits, so the real content, not a
Gotchas (each cost real debugging time): Gotchas (each cost real debugging time):
- **The full prefetch is mandatory.** With App Shells enabled an auto/PPR prefetch bails before the runtime spawn (`subtreeHasSpeculativePrefetch`); use `<Link prefetch={true}>` for normal links, or keep an existing manual full-prefetch abstraction if the app already owns one. If the route is still RED after caching the URL-dependent content, the navigation may still be doing an auto prefetch. - **The full prefetch is mandatory.** With App Shells enabled an auto/PPR prefetch bails before the runtime spawn (`subtreeHasSpeculativePrefetch`); use `<Link prefetch={true}>` for normal links, or keep an existing manual full-prefetch abstraction if the app already owns one. If the route is still RED after caching the URL-dependent content, the navigation may still be doing an auto prefetch.
- **Partial Prefetching must be adopted for the destination.** Runtime prefetching rides on the Partial Prefetching path. If the route is still RED after caching the URL-dependent content, check whether the link is still doing an auto prefetch or whether the destination never adopted Partial Prefetching. - **Partial Prefetching must be adopted for the destination.** Per-link prefetching uses the Partial Prefetching path. If the route is still RED after caching the URL-dependent content, check whether the link is still doing an auto prefetch or whether the destination never adopted Partial Prefetching.
- **Prefetch the canonical URL.** A link whose href 307-redirects (a `/foo` that canonicalizes to `/`) can't be prefetched — the prefetch receives the redirect, not the tree. Point the link and the prefetch at the final URL. - **Prefetch the canonical URL.** A link whose href 307-redirects (a `/foo` that canonicalizes to `/`) can't be prefetched — the prefetch receives the redirect, not the tree. Point the link and the prefetch at the final URL.
- **Don't blanket the full prefetch.** It fetches _all_ the target's dynamic data; enabling it for every visible link is wasteful. Scope `prefetch={true}` to the runtime-prefetch targets only, using the [runtime prefetching trade-offs](https://nextjs.org/docs/app/guides/runtime-prefetching#per-link-prefetching-trade-offs) and [hover-triggered prefetch](https://nextjs.org/docs/app/guides/prefetching#hover-triggered-prefetch) when many links are visible. - **Don't blanket the full prefetch.** It fetches _all_ the target's dynamic data; enabling it for every visible link is wasteful. Scope `prefetch={true}` to the per-link-prefetch targets only, using the [trade-offs](https://nextjs.org/docs/app/guides/optimizing-prefetching#trade-offs) and [hover-triggered prefetch](https://nextjs.org/docs/app/guides/prefetching#hover-triggered-prefetch) when many links are visible.
- **Marker must be a committed node, not RSC bytes.** The content is often a client component, so its text isn't in the prefetch response — assert a `data-testid` that renders when the client subtree commits, not a substring of the stream. - **Marker must be a committed node, not RSC bytes.** The content is often a client component, so its text isn't in the prefetch response — assert a `data-testid` that renders when the client subtree commits, not a substring of the stream.
Prefer a static shell (patterns 1–9) whenever the URL-data read can move: it's cheaper than a runtime prefetch and also covers hard load. Runtime prefetching is only for URL-data reads that genuinely can't move, or routes whose useful content is all URL-specific. Prefer a static shell (patterns 1–9) whenever the URL-data read can move: it's cheaper than a per-link prefetch and also covers hard load. Per-link prefetching is only for URL-data reads that genuinely can't move, or routes whose useful content is all URL-specific.
**Insight:** [dynamic data during prefetching](https://nextjs.org/docs/messages/instant-link-prefetch-partial). **Insight:** [dynamic data during prefetching](https://nextjs.org/docs/messages/instant-link-prefetch-partial).
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