Unverified Commit 68e3fb1d authored by Joseph's avatar Joseph Committed by GitHub

docs: add unstable_navigation and unstable_prefetch API references (#98122)

Adds API reference pages for the two render-interruption functions, both
marked `version: experimental`.

- `unstable_navigation()`, which keeps a subtree out of a route's
prefetches so it renders on the navigation.
- `unstable_prefetch()`, which keeps a subtree out of a route's App
Shell so it renders on a per-link prefetch or on the navigation.

Each page opens with the App Shell, per-link prefetch, navigation
ladder, states which boundary its function moves content past, and
cross-references the sibling function and the Adopting Partial
Prefetching guide.
parent 9d9e1d5b
---
title: unstable_navigation
description: API Reference for the unstable_navigation function, which keeps a subtree out of a route's prefetches so it renders when the user navigates.
version: experimental
related:
links:
- app/api-reference/functions/prefetch
- app/guides/adopting-partial-prefetching
- app/api-reference/functions/io
- app/api-reference/config/next-config-js/partialPrefetching
- app/api-reference/config/next-config-js/cacheComponents
---
Calling `await unstable_navigation()` defers the code below it to the navigation, instead of rendering it when a link to the route is prefetched. The fallback of the nearest [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary takes its place in the prefetch, and the deferred content renders when the user navigates.
It is meant to defer content that a prefetch would otherwise render, even content that would sit in the App Shell, typically because it depends on session data or URL data and is expensive to generate. During a build-time prerender nothing is deferred, so content below `unstable_navigation()` is prerendered as usual.
## Usage
The function requires [Cache Components](/docs/app/api-reference/config/next-config-js/cacheComponents), and throws without it. It is meant for routes using [Partial Prefetching](/docs/app/api-reference/config/next-config-js/partialPrefetching), which you can enable globally or one route at a time by [adopting Partial Prefetching](/docs/app/guides/adopting-partial-prefetching).
```ts filename="next.config.ts" highlight={4,5}
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
cacheComponents: true,
partialPrefetching: true,
}
export default nextConfig
```
A route is then rendered in three stages, and content can arrive at any of them:
1. The [App Shell](/docs/app/glossary#app-shell), which every `<Link>` into the route prefetches, and which holds the part of the route that does not depend on the URL.
2. A per-link prefetch, requested with [`<Link prefetch={true}>`](/docs/app/api-reference/components/link#prefetch), which resolves the URL and adds the content that depends on it.
3. The navigation itself, which covers everything left.
Awaiting `unstable_navigation()` keeps content out of the App Shell and out of per-link prefetches, so it renders only on the navigation.
Without Partial Prefetching, `unstable_navigation()` still defers the content for a default `<Link>`, but [`<Link prefetch={true}>`](/docs/app/api-reference/components/link#prefetch) fetches the whole route, deferred content included, the same as a navigation.
To keep content out of the App Shell while still including it in a per-link prefetch, use [`unstable_prefetch()`](/docs/app/api-reference/functions/prefetch).
Everything above `unstable_navigation()` renders in the prefetch, and everything below renders on the navigation. Deferral is scoped to the component that awaits it and the tree below: sibling branches render in the prefetch as usual. Place it above the code to defer, and wrap the component in [`<Suspense>`](https://react.dev/reference/react/Suspense):
```tsx filename="app/post/[slug]/page.tsx" highlight={20} switcher
import { Suspense } from 'react'
import { cookies } from 'next/headers'
import { cacheLife, unstable_navigation } from 'next/cache'
export default function Page({ params }: PageProps<'/post/[slug]'>) {
return (
<>
<Suspense fallback={<p>Loading post...</p>}>
<PostBody params={params} /> {/* in a per-link prefetch */}
</Suspense>
<Suspense fallback={<p>Loading comments...</p>}>
{/* the fallback is in the prefetch, the comments are not */}
<Comments params={params} />
</Suspense>
</>
)
}
async function Comments({ params }: { params: Promise<{ slug: string }> }) {
await unstable_navigation() // everything below renders on the navigation
const { slug } = await params
const sort = (await cookies()).get('comment-sort')?.value ?? 'newest'
const items = await getComments(slug, sort)
return <CommentList items={items} />
}
async function getComments(slug: string, sort: string) {
'use cache'
cacheLife('hours')
return db.comments.list({ slug, sort })
}
```
```jsx filename="app/post/[slug]/page.js" highlight={20} switcher
import { Suspense } from 'react'
import { cookies } from 'next/headers'
import { cacheLife, unstable_navigation } from 'next/cache'
export default function Page({ params }) {
return (
<>
<Suspense fallback={<p>Loading post...</p>}>
<PostBody params={params} /> {/* in a per-link prefetch */}
</Suspense>
<Suspense fallback={<p>Loading comments...</p>}>
{/* the fallback is in the prefetch, the comments are not */}
<Comments params={params} />
</Suspense>
</>
)
}
async function Comments({ params }) {
await unstable_navigation() // everything below renders on the navigation
const { slug } = await params
const sort = (await cookies()).get('comment-sort')?.value ?? 'newest'
const items = await getComments(slug, sort)
return <CommentList items={items} />
}
async function getComments(slug, sort) {
'use cache'
cacheLife('hours')
return db.comments.list({ slug, sort })
}
```
Comments are fetched by slug, so prefetching them would take a per-link prefetch. Awaiting `unstable_navigation()` before that data access keeps them out of the prefetch, so they render when the user navigates.
The slug and the cookie are both read below `unstable_navigation()` and passed as arguments, so `getComments` caches per post and sort order rather than per visitor. The URL is resolved by the time the deferred content renders, so `params` is available below `unstable_navigation()`.
Put the directive on a function called below it, as `getComments` does here. Awaiting `unstable_navigation()` inside a cached scope, such as [`use cache`](/docs/app/api-reference/directives/use-cache) or [`use cache: private`](/docs/app/api-reference/directives/use-cache-private), is not allowed.
## When to use it
Reach for it when the content below `unstable_navigation()` is expensive to produce, in compute, in upstream requests, or in latency, and you do not want every prefetch of the route to generate it.
Neither prefetch stage runs that code, so its upstream requests are not issued until the user navigates.
Keeping that content out of a prefetch would otherwise mean leaving it uncached.
With `unstable_navigation()` the content can be cached with [`use cache`](/docs/app/api-reference/directives/use-cache), given a lifetime, and deferred to the navigation. Give it a [`stale`](/docs/app/api-reference/functions/cacheLife#stale) time of five minutes or more and the client-side router reuses it after the first time a user navigates into the route. Below that, a [short lifetime keeps it out of the App Shell](/docs/app/api-reference/functions/cacheLife#prerendering-behavior), so each navigation fetches it again.
### Keeping a route's prefetch static
When every read of [`cookies()`](/docs/app/api-reference/functions/cookies), [`headers()`](/docs/app/api-reference/functions/headers), `params`, and `searchParams` sits below `unstable_navigation()`, the prerender a prefetch would trigger cannot produce more than the static output the build already generated, so the prefetch is served from that output instead. Shaping a route this way is an optional optimization: a static response can be cached in a CDN, so a link into the route costs no server CPU at all.
```tsx filename="app/feed/page.tsx" highlight={17}
import { Suspense } from 'react'
import { cookies } from 'next/headers'
import { unstable_navigation } from 'next/cache'
export default function Page() {
return (
<>
<FeedHeader /> {/* static, and so is the whole prefetch */}
<Suspense fallback={<p>Loading stories...</p>}>
<Stories />
</Suspense>
</>
)
}
async function Stories() {
await unstable_navigation()
const topic = (await cookies()).get('topic')?.value ?? 'all'
return <StoryList items={await getStories(topic)} />
}
```
## Good to know
- The function has no effect on the initial load of a page.
- Unlike [`connection()`](/docs/app/api-reference/functions/connection), it does not mark the subtree as request-dependent. Content below `await unstable_navigation()` stays fully cacheable and can be wrapped in [`use cache`](/docs/app/api-reference/directives/use-cache). It also keeps its cache lifetime.
- Reading `cookies()` or `headers()` below `unstable_navigation()` does not make the route's prefetches render per request, so they can still be served from static output. Those accesses are ignored, because they would not have resolved in a prefetch either.
- A call outside a `<Suspense>` boundary surfaces a validation insight in development. It is reported even on a page that is currently prerendered in full, because the same page starts deferring content as soon as it switches to a runtime shell.
- Calling it inside `use cache`, `use cache: private`, [`unstable_cache()`](/docs/app/api-reference/functions/unstable_cache), [`after()`](/docs/app/api-reference/functions/after), [`generateStaticParams`](/docs/app/api-reference/functions/generate-static-params), or a Client Component throws.
{/* TODO: link the validation insight error page from the bullet above once it merges. */}
## Reference
### Type
```ts
function unstable_navigation(): Promise<void>
```
### Parameters
- The function does not accept any parameters.
### Returns
A `Promise<void>`. It is not meant to be consumed.
## Version History
| Version | Changes |
| --------- | ---------------------------- |
| `v16.4.0` | `unstable_navigation` added. |
---
title: unstable_prefetch
description: API Reference for the unstable_prefetch function, which keeps a subtree out of a route's App Shell so it renders on a per-link prefetch or a navigation.
version: experimental
related:
links:
- app/api-reference/functions/navigation
- app/guides/adopting-partial-prefetching
- app/api-reference/functions/io
- app/api-reference/config/next-config-js/partialPrefetching
- app/api-reference/config/next-config-js/cacheComponents
---
Calling `await unstable_prefetch()` defers the code below it to a per-link prefetch or a navigation, instead of rendering it in the route's [App Shell](/docs/app/glossary#app-shell). The fallback of the nearest [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary takes its place in the shell, and the deferred content renders once one of those happens.
It is meant to defer content that the App Shell would otherwise render, typically content that depends on session data and is expensive to generate. During a build-time prerender nothing is deferred, so content below `unstable_prefetch()` is prerendered as usual.
## Usage
The function requires [Cache Components](/docs/app/api-reference/config/next-config-js/cacheComponents) and throws an error if not enabled. Without [Partial Prefetching](/docs/app/api-reference/config/next-config-js/partialPrefetching) a route has no App Shell, so the function has no effect. Enable Partial Prefetching globally, or one route at a time, by [adopting Partial Prefetching](/docs/app/guides/adopting-partial-prefetching).
```ts filename="next.config.ts" highlight={4,5}
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
cacheComponents: true,
partialPrefetching: true,
}
export default nextConfig
```
A route is then rendered in three stages, and content can arrive at any of them:
1. The App Shell, which every `<Link>` into the route prefetches, and which holds the part of the route that does not depend on the URL.
2. A per-link prefetch, requested with [`<Link prefetch={true}>`](/docs/app/api-reference/components/link#prefetch), which resolves the URL and adds the content that depends on it.
3. The navigation itself, which covers everything left.
Awaiting `unstable_prefetch()` keeps content out of the App Shell, so it renders only on a per-link prefetch or on the navigation.
To keep content out of per-link prefetches as well, so it renders only on the navigation, use [`unstable_navigation()`](/docs/app/api-reference/functions/navigation).
Everything above `unstable_prefetch()` renders in the App Shell, and everything below renders on a per-link prefetch or on the navigation. Deferral is scoped to the component that awaits it and the tree below: sibling branches render in the shell as usual. Place it above the work to defer, and wrap the component in [`<Suspense>`](https://react.dev/reference/react/Suspense):
```tsx filename="app/dashboard/page.tsx" highlight={25} switcher
import { Suspense } from 'react'
import { cookies } from 'next/headers'
import { cacheLife, unstable_prefetch } from 'next/cache'
export default function Page() {
return (
<>
<Suspense fallback={<p>Loading greeting...</p>}>
<Greeting /> {/* in the App Shell */}
</Suspense>
<Suspense fallback={<p>Loading recommendations...</p>}>
{/* the fallback is in the App Shell, the recommendations are not */}
<Recommendations />
</Suspense>
</>
)
}
async function Greeting() {
const session = (await cookies()).get('session')?.value
return <p>{session ? 'Welcome back' : 'Welcome'}</p>
}
async function Recommendations() {
await unstable_prefetch() // everything below renders on a per-link prefetch
const items = await getRecommendations()
return <List items={items} />
}
async function getRecommendations() {
'use cache: private'
cacheLife('hours')
const session = (await cookies()).get('session')?.value
return db.recommendations.rank({ session })
}
```
```jsx filename="app/dashboard/page.js" highlight={25} switcher
import { Suspense } from 'react'
import { cookies } from 'next/headers'
import { cacheLife, unstable_prefetch } from 'next/cache'
export default function Page() {
return (
<>
<Suspense fallback={<p>Loading greeting...</p>}>
<Greeting /> {/* in the App Shell */}
</Suspense>
<Suspense fallback={<p>Loading recommendations...</p>}>
{/* the fallback is in the App Shell, the recommendations are not */}
<Recommendations />
</Suspense>
</>
)
}
async function Greeting() {
const session = (await cookies()).get('session')?.value
return <p>{session ? 'Welcome back' : 'Welcome'}</p>
}
async function Recommendations() {
await unstable_prefetch() // everything below renders on a per-link prefetch
const items = await getRecommendations()
return <List items={items} />
}
async function getRecommendations() {
'use cache: private'
cacheLife('hours')
const session = (await cookies()).get('session')?.value
return db.recommendations.rank({ session })
}
```
The greeting reads the session and stays in the App Shell. The recommendations read it too, inside `getRecommendations`, so that read is deferred along with the ranking. Remove `unstable_prefetch()` and they become part of the App Shell that every link into the route prefetches.
Put the directive on a function called below it, as `getRecommendations` does here. Awaiting `unstable_prefetch()` inside a cached scope, such as [`use cache`](/docs/app/api-reference/directives/use-cache) or [`use cache: private`](/docs/app/api-reference/directives/use-cache-private), is not allowed.
## When to use it
Reach for it when the content below `unstable_prefetch()` is expensive to produce, in compute, in upstream requests, or in latency, and you do not want it generated in the App Shell that every `<Link>` into the route prefetches.
Producing the App Shell does not run that code, so its upstream requests are not issued until a per-link prefetch or the navigation.
Keeping that content out of the shell would otherwise mean leaving it uncached. With `unstable_prefetch()` it can be cached with [`use cache`](/docs/app/api-reference/directives/use-cache) or [`use cache: private`](/docs/app/api-reference/directives/use-cache-private), given a lifetime, and deferred to a per-link prefetch or the navigation.
Uncached reads, values with a short [`stale`](/docs/app/api-reference/functions/cacheLife#stale) time, and anything behind `params` or `searchParams` are already left out of the shell on their own.
### Keeping the App Shell static
When every read of [`cookies()`](/docs/app/api-reference/functions/cookies) and [`headers()`](/docs/app/api-reference/functions/headers) sits below `unstable_prefetch()`, the prerender a shell prefetch would trigger cannot produce more than the static output the build already generated, so the shell is served from that output instead. Shaping a route this way is an optional optimization: a static response can be cached in a CDN, so a default `<Link>` into the route costs no server CPU at all. A route that resolves `params` or `searchParams` gets that prerender instead, and so does the example above: its greeting reads the session in the shell, so the shell renders once per visitor and only the recommendations are deferred.
## Good to know
- The function has no effect on the initial load of a page.
- Unlike [`connection()`](/docs/app/api-reference/functions/connection), it does not mark the subtree as request-dependent. Content below `await unstable_prefetch()` stays fully cacheable and can be wrapped in [`use cache`](/docs/app/api-reference/directives/use-cache).
- A call outside a `<Suspense>` boundary surfaces a validation insight in development. It is reported even on a page that is currently prerendered in full, because the same page starts deferring content as soon as it switches to a runtime shell.
- Calling it inside `use cache`, `use cache: private`, [`unstable_cache()`](/docs/app/api-reference/functions/unstable_cache), [`after()`](/docs/app/api-reference/functions/after), [`generateStaticParams`](/docs/app/api-reference/functions/generate-static-params), or a Client Component throws.
{/* TODO: link the validation insight error page from the bullet above once it merges. */}
## Reference
### Type
```ts
function unstable_prefetch(): Promise<void>
```
### Parameters
- The function does not accept any parameters.
### Returns
A `Promise<void>`. It is not meant to be consumed.
## Version History
| Version | Changes |
| --------- | -------------------------- |
| `v16.4.0` | `unstable_prefetch` added. |
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