Unverified Commit 3452ebbc authored by Joseph's avatar Joseph Committed by GitHub

Remove unstable_ prefix from navigation() and prefetch() (#99241)

Remove unstable_ prefixes from navigation and prefetch in the entire
codebase.


[NAR-932](https://linear.app/vercel/issue/NAR-932/remove-prefixes-from-unstable-navigation-unstable-prefetch)
parent 72003a79
......@@ -725,8 +725,8 @@ impl ReactServerComponentValidator {
"unstable_cacheLife",
"cacheTag",
"unstable_cacheTag",
"unstable_navigation",
"unstable_prefetch",
"navigation",
"prefetch",
// "unstable_noStore" // no-op in client, but allowed for legacy reasons
],
),
......
import { unstable_prefetch } from 'next/cache'
import { navigation } from 'next/cache'
export async function test() {
await unstable_prefetch()
await navigation()
return null
}
import { unstable_prefetch } from 'next/cache';
import { navigation } from 'next/cache';
export async function test() {
await unstable_prefetch();
await navigation();
return null;
}
x You're importing a module that depends on "navigation" into a React Client Component module. This API is only available in Server Components but one of its parents is marked with "use client",
| so this module is also a Client Component.
| Learn more: https://nextjs.org/docs/app/building-your-application/rendering
|
|
,-[input.js:1:1]
1 | import { navigation } from 'next/cache'
: ^^^^^^^^^^
`----
import { unstable_prefetch } from 'next/cache'
import { prefetch } from 'next/cache'
export async function test() {
await unstable_prefetch()
await prefetch()
return null
}
import { unstable_prefetch } from 'next/cache';
import { prefetch } from 'next/cache';
export async function test() {
await unstable_prefetch();
await prefetch();
return null;
}
x You're importing a module that depends on "prefetch" into a React Client Component module. This API is only available in Server Components but one of its parents is marked with "use client", so
| this module is also a Client Component.
| Learn more: https://nextjs.org/docs/app/building-your-application/rendering
|
|
,-[input.js:1:1]
1 | import { prefetch } from 'next/cache'
: ^^^^^^^^
`----
x You're importing a module that depends on "unstable_navigation" into a React Client Component module. This API is only available in Server Components but one of its parents is marked with "use
| client", so this module is also a Client Component.
| Learn more: https://nextjs.org/docs/app/building-your-application/rendering
|
|
,-[input.js:1:1]
1 | import { unstable_navigation } from 'next/cache'
: ^^^^^^^^^^^^^^^^^^^
`----
x You're importing a module that depends on "unstable_prefetch" into a React Client Component module. This API is only available in Server Components but one of its parents is marked with "use
| client", so this module is also a Client Component.
| Learn more: https://nextjs.org/docs/app/building-your-application/rendering
|
|
,-[input.js:1:1]
1 | import { unstable_prefetch } from 'next/cache'
: ^^^^^^^^^^^^^^^^^
`----
import { unstable_navigation } from 'next/cache'
import { navigation } from 'next/cache'
export async function test() {
await unstable_navigation()
await navigation()
return null
}
import { unstable_navigation } from 'next/cache';
import { navigation } from 'next/cache';
export async function test() {
await unstable_navigation();
await navigation();
return null;
}
x You're importing a module that depends on "unstable_prefetch". This API is only available in Server Components in the App Router, but you are using it in the Pages Router.
x You're importing a module that depends on "navigation". This API is only available in Server Components in the App Router, but you are using it in the Pages Router.
| Learn more: https://nextjs.org/docs/app/building-your-application/rendering/server-components
|
|
,-[input.js:1:1]
1 | import { unstable_prefetch } from 'next/cache'
: ^^^^^^^^^^^^^^^^^
1 | import { navigation } from 'next/cache'
: ^^^^^^^^^^
`----
import { unstable_navigation } from 'next/cache'
import { prefetch } from 'next/cache'
export async function test() {
await unstable_navigation()
await prefetch()
return null
}
import { unstable_navigation } from 'next/cache';
import { prefetch } from 'next/cache';
export async function test() {
await unstable_navigation();
await prefetch();
return null;
}
x You're importing a module that depends on "unstable_navigation". This API is only available in Server Components in the App Router, but you are using it in the Pages Router.
x You're importing a module that depends on "prefetch". This API is only available in Server Components in the App Router, but you are using it in the Pages Router.
| Learn more: https://nextjs.org/docs/app/building-your-application/rendering/server-components
|
|
,-[input.js:1:1]
1 | import { unstable_navigation } from 'next/cache'
: ^^^^^^^^^^^^^^^^^^^
1 | import { prefetch } from 'next/cache'
: ^^^^^^^^
`----
......@@ -345,6 +345,8 @@ Each card is clickable and opens a page with patterns, code samples, and trade-o
}
```
> **Good to know**: If the page or layout already calls [`prefetch()`](/docs/app/api-reference/functions/prefetch), import it under another name, for example `import { prefetch as prefetchStage } from 'next/cache'`, so it doesn't collide with the `prefetch` export.
2. Deploy the change. Links to the adopted destination load the App Shell, and the insight keeps surfacing for the destinations you haven't reached.
3. Repeat until every destination in scope is adopted, then [enable the flag](#enable-partial-prefetching).
......
......@@ -198,15 +198,15 @@ Everything inside the scope shares the same lifetime. Colocate `"use cache: priv
Optimizing a prefetch also means excluding content from it. Some subtrees are expensive enough to produce that you would rather not pay for them on every prefetch of the route.
Awaiting [`unstable_navigation()`](/docs/app/api-reference/functions/navigation) above the work leaves it out of every prefetch, so it is produced on the navigation. The nearest [`<Suspense>`](https://react.dev/reference/react/Suspense) fallback is what the user sees while it streams in. Take the dashboard again, where a ranking keyed on the session is too expensive to produce for every link into the route:
Awaiting [`navigation()`](/docs/app/api-reference/functions/navigation) above the work leaves it out of every prefetch, so it is produced on the navigation. The nearest [`<Suspense>`](https://react.dev/reference/react/Suspense) fallback is what the user sees while it streams in. Take the dashboard again, where a ranking keyed on the session is too expensive to produce for every link into the route:
```tsx filename="app/dashboard/recommendations.tsx" highlight={6}
import { cookies } from 'next/headers'
import { unstable_navigation } from 'next/cache'
import { navigation } from 'next/cache'
async function Recommendations() {
const session = (await cookies()).get('session')?.value
await unstable_navigation()
await navigation()
const items = await rank(session)
return <List items={items} />
}
......@@ -217,13 +217,13 @@ async function rank(session?: string) {
}
```
The session is read above `unstable_navigation()`, so it resolves in the shell like any other session data. Only the ranking is left out, and it keeps its cache lifetime.
The session is read above `navigation()`, so it resolves in the shell like any other session data. Only the ranking is left out, and it keeps its cache lifetime.
Without it, keeping a subtree out of a prefetch means leaving it uncached, which gives up that lifetime on the navigation too. Awaiting `unstable_navigation()` inside a cached scope is not allowed, so put the caching directive on a function called below it, as `rank` does here.
Without it, keeping a subtree out of a prefetch means leaving it uncached, which gives up that lifetime on the navigation too. Awaiting `navigation()` inside a cached scope is not allowed, so put the caching directive on a function called below it, as `rank` does here.
For a subtree that would otherwise sit in the App Shell, but that a `<Link prefetch={true}>` should still resolve before the click, use [`unstable_prefetch()`](/docs/app/api-reference/functions/prefetch) instead.
For a subtree that would otherwise sit in the App Shell, but that a `<Link prefetch={true}>` should still resolve before the click, use [`prefetch()`](/docs/app/api-reference/functions/prefetch) instead.
Unlike [`connection()`](/docs/app/api-reference/functions/connection), `unstable_navigation()` does not make the subtree request-dependent. This lets reusable content keep its cache lifetime while waiting for navigation. See [How `unstable_navigation()` differs from `connection()`](/docs/app/api-reference/functions/navigation#how-unstable_navigation-differs-from-connection) for the full comparison.
Unlike [`connection()`](/docs/app/api-reference/functions/connection), `navigation()` does not make the subtree request-dependent. This lets reusable content keep its cache lifetime while waiting for navigation. See [How `navigation()` differs from `connection()`](/docs/app/api-reference/functions/navigation#how-navigation-differs-from-connection) for the full comparison.
## Test prefetched and deferred content
......@@ -291,6 +291,6 @@ When many links to a route are visible at once, such as a grid of cards, each `<
- [Adopting Partial Prefetching](/docs/app/guides/adopting-partial-prefetching) for how `<Link>` behaves under the new model and how to migrate existing apps.
- [`prefetch` API reference](/docs/app/api-reference/file-conventions/route-segment-config/prefetch) for all prefetch modes.
- [`use cache: private` reference](/docs/app/api-reference/directives/use-cache-private) for per-user caching specifics.
- [`unstable_prefetch()`](/docs/app/api-reference/functions/prefetch) and [`unstable_navigation()`](/docs/app/api-reference/functions/navigation) for the full behavior of each prefetch stage.
- [`prefetch()`](/docs/app/api-reference/functions/prefetch) and [`navigation()`](/docs/app/api-reference/functions/navigation) for the full behavior of each prefetch stage.
- [Instant navigation guide](/docs/app/guides/instant-navigation) for validating the route's caching structure.
- [Caching](/docs/app/getting-started/caching) for background on `use cache`, Suspense, and Partial Prerendering.
......@@ -16,6 +16,7 @@ The `prefetch` route segment config controls how a segment is prefetched during
> - The `prefetch` export only works when [`cacheComponents`](/docs/app/api-reference/config/next-config-js/cacheComponents) is enabled.
> - `prefetch` cannot be used when the segment is a Client Component.
> - The meaningful values to set are `'partial'` and `'force-disabled'`. `'auto'` is the default and is equivalent to omitting the export; don't write `prefetch = 'auto'` explicitly.
> - A `page` or `layout` that also calls the [`prefetch()`](/docs/app/api-reference/functions/prefetch) function needs to import it under another name, for example `import { prefetch as prefetchStage } from 'next/cache'`.
```tsx filename="layout.tsx | page.tsx" switcher
export const prefetch = 'partial'
......
---
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
title: navigation
description: API Reference for the navigation function, which keeps a subtree out of a route's prefetches so it renders when the user navigates.
related:
links:
- app/api-reference/functions/prefetch
......@@ -12,9 +11,9 @@ related:
- 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.
Calling `await navigation()` defers the code below it to the navigation, instead of rendering it when a link to the route is prefetched. The fallback of the nearest [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary takes its place in the prefetch, and the deferred content renders when the user navigates.
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.
It is meant to defer content that a prefetch would otherwise render, even content that would sit in the App Shell, typically because it depends on session data or URL data and is expensive to generate. During a build-time prerender nothing is deferred, so content below `navigation()` is prerendered as usual.
## Usage
......@@ -37,18 +36,18 @@ A route is then rendered in three stages, and content can arrive at any of them:
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.
Awaiting `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.
Without Partial Prefetching, `navigation()` still defers the content for a default `<Link>`, but [`<Link prefetch={true}>`](/docs/app/api-reference/components/link#prefetch) fetches the whole route, deferred content included, the same as a navigation.
To keep content out of the App Shell while still including it in a per-link prefetch, use [`unstable_prefetch()`](/docs/app/api-reference/functions/prefetch).
To keep content out of the App Shell while still including it in a per-link prefetch, use [`prefetch()`](/docs/app/api-reference/functions/prefetch).
Everything above `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):
Everything above `navigation()` renders in the prefetch, and everything below renders on the navigation. Deferral is scoped to the component that awaits it and the tree below: sibling branches render in the prefetch as usual. Place it above the code to defer, and wrap the component in [`<Suspense>`](https://react.dev/reference/react/Suspense):
```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'
import { cacheLife, navigation } from 'next/cache'
export default function Page({ params }: PageProps<'/post/[slug]'>) {
return (
......@@ -65,7 +64,7 @@ export default function Page({ params }: PageProps<'/post/[slug]'>) {
}
async function Comments({ params }: { params: Promise<{ slug: string }> }) {
await unstable_navigation() // everything below renders on the navigation
await 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)
......@@ -82,7 +81,7 @@ async function getComments(slug: string, sort: string) {
```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'
import { cacheLife, navigation } from 'next/cache'
export default function Page({ params }) {
return (
......@@ -99,7 +98,7 @@ export default function Page({ params }) {
}
async function Comments({ params }) {
await unstable_navigation() // everything below renders on the navigation
await 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)
......@@ -113,38 +112,38 @@ async function getComments(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.
Comments are fetched by slug, so prefetching them would take a per-link prefetch. Awaiting `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()`.
The slug and the cookie are both read below `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 `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.
Put the directive on a function called below it, as `getComments` does here. Awaiting `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.
## How `unstable_navigation()` differs from `connection()`
## How `navigation()` differs from `connection()`
The [`connection()`](/docs/app/api-reference/functions/connection) function waits for a real request. It excludes the code that follows from prerendering and prefetching, making that work request-dependent.
`unstable_navigation()` only excludes the code that follows from route prefetches. It resolves when the user navigates without making that work request-dependent. A function called after `await unstable_navigation()` can therefore use [`"use cache"`](/docs/app/api-reference/directives/use-cache) and keep its cache lifetime without generating its result during prefetching.
`navigation()` only excludes the code that follows from route prefetches. It resolves when the user navigates without making that work request-dependent. A function called after `await navigation()` can therefore use [`"use cache"`](/docs/app/api-reference/directives/use-cache) and keep its cache lifetime without generating its result during prefetching.
Use `connection()` when the work must run for a real request. Use `unstable_navigation()` when the work is reusable but should wait until the user navigates.
Use `connection()` when the work must run for a real request. Use `navigation()` when the work is reusable but should wait until the user navigates.
## When to use it
Reach for it when the content below `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.
Reach for it when the content below `navigation()` is expensive to produce, in compute, in upstream requests, or in latency, and you do not want every prefetch of the route to generate it.
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.
With `navigation()` the content can be cached with [`use cache`](/docs/app/api-reference/directives/use-cache), given a lifetime, and deferred to the navigation. Give it a [`stale`](/docs/app/api-reference/functions/cacheLife#stale) time of five minutes or more and the client-side router reuses it after the first time a user navigates into the route. Below that, a [short lifetime keeps it out of the App Shell](/docs/app/api-reference/functions/cacheLife#prerendering-behavior), so each navigation fetches it again.
### 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.
When every read of [`cookies()`](/docs/app/api-reference/functions/cookies), [`headers()`](/docs/app/api-reference/functions/headers), `params`, and `searchParams` sits below `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'
import { navigation } from 'next/cache'
export default function Page() {
return (
......@@ -158,7 +157,7 @@ export default function Page() {
}
async function Stories() {
await unstable_navigation()
await navigation()
const topic = (await cookies()).get('topic')?.value ?? 'all'
return <StoryList items={await getStories(topic)} />
}
......@@ -167,7 +166,7 @@ async function Stories() {
## Good to know
- The function has no effect on the initial load of a page.
- 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.
- Reading `cookies()` or `headers()` below `navigation()` does not make the route's prefetches render per request, so they can still be served from static output. Those accesses are ignored, because they would not have resolved in a prefetch either.
- A call outside a `<Suspense>` boundary surfaces 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.
......@@ -178,7 +177,7 @@ async function Stories() {
### Type
```ts
function unstable_navigation(): Promise<void>
function navigation(): Promise<void>
```
### Parameters
......@@ -191,6 +190,6 @@ A `Promise<void>`. It is not meant to be consumed.
## Version History
| Version | Changes |
| --------- | ---------------------------- |
| `v16.4.0` | `unstable_navigation` added. |
| Version | Changes |
| --------- | ------------------- |
| `v16.4.0` | `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
title: prefetch
description: API Reference for the prefetch function, which keeps a subtree out of a route's App Shell so it renders on a per-link prefetch or a navigation.
related:
links:
- app/api-reference/functions/navigation
......@@ -12,9 +11,9 @@ related:
- 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.
Calling `await prefetch()` defers the code below it to a per-link prefetch or a navigation, instead of rendering it in the route's [App Shell](/docs/app/glossary#app-shell). The fallback of the nearest [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary takes its place in the shell, and the deferred content renders once one of those happens.
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.
It is meant to defer content that the App Shell would otherwise render, typically content that depends on session data and is expensive to generate. During a build-time prerender nothing is deferred, so content below `prefetch()` is prerendered as usual.
## Usage
......@@ -37,16 +36,16 @@ A route is then rendered in three stages, and content can arrive at any of them:
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.
Awaiting `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).
To keep content out of per-link prefetches as well, so it renders only on the navigation, use [`navigation()`](/docs/app/api-reference/functions/navigation).
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):
Everything above `prefetch()` renders in the App Shell, and everything below renders on a per-link prefetch or on the navigation. Deferral is scoped to the component that awaits it and the tree below: sibling branches render in the shell as usual. Place it above the work to defer, and wrap the component in [`<Suspense>`](https://react.dev/reference/react/Suspense):
```tsx filename="app/dashboard/page.tsx" highlight={25} switcher
import { Suspense } from 'react'
import { cookies } from 'next/headers'
import { cacheLife, unstable_prefetch } from 'next/cache'
import { cacheLife, prefetch } from 'next/cache'
export default function Page() {
return (
......@@ -68,7 +67,7 @@ async function Greeting() {
}
async function Recommendations() {
await unstable_prefetch() // everything below renders on a per-link prefetch
await prefetch() // everything below renders on a per-link prefetch
const items = await getRecommendations()
return <List items={items} />
}
......@@ -84,7 +83,7 @@ async function getRecommendations() {
```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'
import { cacheLife, prefetch } from 'next/cache'
export default function Page() {
return (
......@@ -106,7 +105,7 @@ async function Greeting() {
}
async function Recommendations() {
await unstable_prefetch() // everything below renders on a per-link prefetch
await prefetch() // everything below renders on a per-link prefetch
const items = await getRecommendations()
return <List items={items} />
}
......@@ -119,37 +118,38 @@ async function getRecommendations() {
}
```
The greeting reads the session and stays in the App Shell. The recommendations read it too, inside `getRecommendations`, so that read is deferred along with the ranking. Remove `unstable_prefetch()` and they become part of the App Shell that every link into the route prefetches.
The greeting reads the session and stays in the App Shell. The recommendations read it too, inside `getRecommendations`, so that read is deferred along with the ranking. Remove `prefetch()` and they become part of the App Shell that every link into the route 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.
Put the directive on a function called below it, as `getRecommendations` does here. Awaiting `prefetch()` inside a cached scope, such as [`use cache`](/docs/app/api-reference/directives/use-cache) or [`use cache: private`](/docs/app/api-reference/directives/use-cache-private), is not allowed.
## How `unstable_prefetch()` differs from `connection()`
## How `prefetch()` differs from `connection()`
The [`connection()`](/docs/app/api-reference/functions/connection) function waits for a real request. It excludes the code that follows from prerendering and prefetching, making that work request-dependent.
`unstable_prefetch()` only excludes the code that follows from the App Shell. It can resolve during a per-link prefetch without making that work request-dependent. A function called after `await unstable_prefetch()` can therefore use [`"use cache"`](/docs/app/api-reference/directives/use-cache) and keep its cache lifetime without generating its result for every link into the route.
`prefetch()` only excludes the code that follows from the App Shell. It can resolve during a per-link prefetch without making that work request-dependent. A function called after `await prefetch()` can therefore use [`"use cache"`](/docs/app/api-reference/directives/use-cache) and keep its cache lifetime without generating its result for every link into the route.
Use `connection()` when the work must run for a real request. Use `unstable_prefetch()` when the work is reusable but should only run for a selected per-link prefetch or a navigation.
Use `connection()` when the work must run for a real request. Use `prefetch()` when the work is reusable but should only run for a selected per-link prefetch or a navigation.
## When to use it
Reach for it when the content below `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.
Reach for it when the content below `prefetch()` is expensive to produce, in compute, in upstream requests, or in latency, and you do not want it generated in the App Shell that every `<Link>` into the route prefetches.
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.
Keeping that content out of the shell would otherwise mean leaving it uncached. With `prefetch()` it can be cached with [`use cache`](/docs/app/api-reference/directives/use-cache) or [`use cache: private`](/docs/app/api-reference/directives/use-cache-private), given a lifetime, and deferred to a per-link prefetch or the navigation.
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.
When every read of [`cookies()`](/docs/app/api-reference/functions/cookies) and [`headers()`](/docs/app/api-reference/functions/headers) sits below `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.
- 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.
- In a `page` or `layout` that sets the [`prefetch` route segment config](/docs/app/api-reference/file-conventions/route-segment-config/prefetch), import the function under another name, for example `import { prefetch as prefetchStage } from 'next/cache'`, since both are named `prefetch`.
{/* TODO: link the validation insight error page from the bullet above once it merges. */}
......@@ -158,7 +158,7 @@ When every read of [`cookies()`](/docs/app/api-reference/functions/cookies) and
### Type
```ts
function unstable_prefetch(): Promise<void>
function prefetch(): Promise<void>
```
### Parameters
......@@ -171,6 +171,6 @@ A `Promise<void>`. It is not meant to be consumed.
## Version History
| Version | Changes |
| --------- | -------------------------- |
| `v16.4.0` | `unstable_prefetch` added. |
| Version | Changes |
| --------- | ----------------- |
| `v16.4.0` | `prefetch` added. |
......@@ -70,7 +70,9 @@ test('caches the category data', () => {
})
test('does not use a navigation-stage boundary', () => {
expect(source).not.toMatch(/\bunstable_navigation\b/)
expect(source).not.toMatch(
/import\s*\{[^}]*\bnavigation\b[^}]*\}\s*from\s*['"]next\/cache['"]/
)
})
test('prefetches the selected category and cached products', async () => {
......@@ -79,6 +81,6 @@ test('prefetches the selected category and cached products', async () => {
A correct solution preserves the existing /catalog?category=... URLs, enables Partial Prefetching globally or on the catalog route, and opts the category Links into per-link prefetching with prefetch={true} or the equivalent bare prefetch prop. The catalog route reads the category from searchParams beneath Suspense and renders both the matching heading and getProducts(category) result in the prefetched result. The category data must use a use cache scope, with either the default cache profile or an explicit cacheLife(); searchParams must remain outside that cache scope. Keep the Suspense boundary: the shared App Shell uses its fallback, while a completed per-link prefetch can resolve the cached content inside it before navigation.
This is the basic URL-data inclusion case. Do not use unstable_navigation(), unstable_prefetch(), connection(), or an uncached request boundary to defer the category content. Reject solutions that only prefetch the reusable Catalog shell while leaving the selected heading or product list behind the loading fallback.`
This is the basic URL-data inclusion case. Do not use navigation(), prefetch(), connection(), or an uncached request boundary to defer the category content. Reject solutions that only prefetch the reusable Catalog shell while leaving the selected heading or product list behind the loading fallback.`
)
})
......@@ -62,11 +62,11 @@ test('opts the featured product link into per-link prefetching', () => {
test('uses the prefetch cache stage', () => {
const prefetchImport = source.match(
/\bunstable_prefetch(?:\s+as\s+([A-Za-z_$][\w$]*))?/
/import\s*\{[^}]*\bprefetch\b(?:\s+as\s+([A-Za-z_$][\w$]*))?[^}]*\}\s*from\s*['"]next\/cache['"]/
)
expect(prefetchImport).not.toBeNull()
const localName = prefetchImport?.[1] ?? 'unstable_prefetch'
const localName = prefetchImport?.[1] ?? 'prefetch'
expect(source).toMatch(new RegExp(`await\\s+${localName}\\s*\\(`))
})
......@@ -80,8 +80,8 @@ test('includes related products only in the selected prefetch', async () => {
await expect(environment).toSatisfyCriterion(
`The related-products section must be available before navigation from the featured-product Link without joining the default product App Shell.
Render related products through an async component that awaits unstable_prefetch() before calling the cached getRelatedProducts() function. The unstable_prefetch() call must be outside every use cache scope, while the existing cached data function stays below it.
Render related products through an async component that awaits prefetch() before calling the cached getRelatedProducts() function. The prefetch() call must be outside every use cache scope, while the existing cached data function stays below it.
Reject solutions that replace the stage with connection() or unstable_navigation(), make the related-products data uncached, or defer it until after navigation. Accept equivalent component and file organization.`
Reject solutions that replace the stage with connection() or navigation(), make the related-products data uncached, or defer it until after navigation. Accept equivalent component and file organization.`
)
})
......@@ -63,11 +63,11 @@ test('opts the project link into per-link prefetching', () => {
test('uses the navigation cache stage', () => {
const navigationImport = source.match(
/\bunstable_navigation(?:\s+as\s+([A-Za-z_$][\w$]*))?/
/import\s*\{[^}]*\bnavigation\b(?:\s+as\s+([A-Za-z_$][\w$]*))?[^}]*\}\s*from\s*['"]next\/cache['"]/
)
expect(navigationImport).not.toBeNull()
const localName = navigationImport?.[1] ?? 'unstable_navigation'
const localName = navigationImport?.[1] ?? 'navigation'
expect(source).toMatch(new RegExp(`await\\s+${localName}\\s*\\(`))
})
......@@ -75,14 +75,14 @@ test('includes the project title in the selected prefetch', async () => {
await expect(environment).toSatisfyCriterion(
`The selected project's title must be available before the click from the dashboard's per-link prefetch. Keep the params-dependent title inside Suspense so the reusable App Shell can show a fallback while the selected prefetch resolves the title. The title must render before the nested boundary that waits for navigation.
Accept equivalent component and file organization. Reject solutions that leave the title behind the reusable shell fallback, put it behind unstable_navigation(), disable prefetching, or prefetch the entire page.`
Accept equivalent component and file organization. Reject solutions that leave the title behind the reusable shell fallback, put it behind navigation(), disable prefetching, or prefetch the entire page.`
)
})
test('waits until navigation for project details', async () => {
await expect(environment).toSatisfyCriterion(
`Project activity, deployments, description, and other detail content must not join the prefetch. Render those details inside a nested Suspense boundary through an async component that awaits unstable_navigation() before loading or rendering them.
`Project activity, deployments, description, and other detail content must not join the prefetch. Render those details inside a nested Suspense boundary through an async component that awaits navigation() before loading or rendering them.
The unstable_navigation() call must remain outside every use cache scope; cached data functions may be called after it. Reject solutions that fetch project details before reaching unstable_navigation(), replace it with connection() or an uncached fetch, or prefetch the entire page. Accept equivalent component and file organization.`
The navigation() call must remain outside every use cache scope; cached data functions may be called after it. Reject solutions that fetch project details before reaching navigation(), replace it with connection() or an uncached fetch, or prefetch the entire page. Accept equivalent component and file organization.`
)
})
......@@ -164,5 +164,5 @@ export function cacheLife(profile: {
export const unstable_cacheLife: typeof cacheLife
export const unstable_cacheTag: typeof cacheTag
export { unstable_navigation } from 'next/dist/server/request/cache-stages'
export { unstable_prefetch } from 'next/dist/server/request/cache-stages'
export { navigation } from 'next/dist/server/request/cache-stages'
export { prefetch } from 'next/dist/server/request/cache-stages'
......@@ -25,8 +25,8 @@ if (process.env.NEXT_RUNTIME === '') {
refresh: notAvailableInClient('refresh'),
cacheLife: notAvailableInClient('cacheLife'),
cacheTag: notAvailableInClient('cacheTag'),
unstable_navigation: notAvailableInClient('unstable_navigation'),
unstable_prefetch: notAvailableInClient('unstable_prefetch'),
navigation: notAvailableInClient('navigation'),
prefetch: notAvailableInClient('prefetch'),
}
} else {
// Keep server requires in this branch so browser builds can DCE them.
......@@ -51,10 +51,8 @@ if (process.env.NEXT_RUNTIME === '') {
io: require('next/dist/server/request/io').io,
cacheLife: require('next/dist/server/use-cache/cache-life').cacheLife,
cacheTag: require('next/dist/server/use-cache/cache-tag').cacheTag,
unstable_navigation: require('next/dist/server/request/cache-stages')
.unstable_navigation,
unstable_prefetch: require('next/dist/server/request/cache-stages')
.unstable_prefetch,
navigation: require('next/dist/server/request/cache-stages').navigation,
prefetch: require('next/dist/server/request/cache-stages').prefetch,
}
}
......@@ -101,5 +99,5 @@ exports.cacheTag = cacheExports.cacheTag
exports.unstable_cacheTag = cacheExports.unstable_cacheTag
exports.refresh = cacheExports.refresh
exports.io = cacheExports.io
exports.unstable_navigation = cacheExports.unstable_navigation
exports.unstable_prefetch = cacheExports.unstable_prefetch
exports.navigation = cacheExports.navigation
exports.prefetch = cacheExports.prefetch
......@@ -358,7 +358,7 @@ export function getGuidanceVariant(message: string): GuidanceVariant {
// Discriminates between `createNavigationBodyErrorInNavigation`,
// `createLinkBodyErrorInNavigation`, `createRuntimeBodyError`, and
// `createDynamicBodyError` (and their in-navigation variants).
if (message.includes('encountered `unstable_navigation()`')) {
if (message.includes('encountered `navigation()`')) {
return 'navigation'
}
if (
......@@ -900,8 +900,7 @@ export function Errors({
case 'navigation':
errorMessage = (
<>
Next.js encountered <code>unstable_navigation()</code> outside of
Suspense.
Next.js encountered <code>navigation()</code> outside of Suspense.
</>
)
break
......@@ -1020,7 +1019,7 @@ export function Errors({
case 'navigation':
errorMessage = (
<>
Next.js encountered <code>unstable_navigation()</code> in{' '}
Next.js encountered <code>navigation()</code> in{' '}
<code>generateMetadata()</code>.
</>
)
......@@ -1095,7 +1094,7 @@ export function Errors({
case 'navigation':
errorMessage = (
<>
Next.js encountered <code>unstable_navigation()</code> in{' '}
Next.js encountered <code>navigation()</code> in{' '}
<code>generateViewport()</code>.
</>
)
......
......@@ -5222,7 +5222,7 @@ async function prepareValidationInputsInPartialPrefetching(
// (see `needsRuntimeShell` and callsites of `trackIncompatibleShellContent`)
// This includes:
// - static `params`
// - `unstable_navigation()` and `unstable_prefetch()`
// - `navigation()` and `prefetch()`
// - caches with `stale < MIN_SHELL_STALE` are excluded from app shells
// but are included in static prerenders
// If one of these APIs is used, the render can't be used for both Instant Validation and
......
......@@ -46,8 +46,8 @@ export function createLinkBodyErrorInNavigation(route: string): Error {
export function createNavigationBodyErrorInNavigation(route: string): Error {
// TODO(cache-stages): docs link
return new Error(
`Route "${route}": Next.js encountered \`unstable_navigation()\` during prerendering or a navigation.\n\n` +
`\`unstable_navigation()\` called outside of \`<Suspense>\` may prevent the navigation from being instant, leading to a slower user experience.\n\n` +
`Route "${route}": Next.js encountered \`navigation()\` during prerendering or a navigation.\n\n` +
`\`navigation()\` called outside of \`<Suspense>\` may prevent the navigation from being instant, leading to a slower user experience.\n\n` +
`Ways to fix this:\n` +
` - [stream] Provide a placeholder with \`<Suspense fallback={...}>\` around the data access\n` +
` - [block] Set \`export const instant = false\` to allow a blocking route\n\n` +
......@@ -109,8 +109,8 @@ export function createRuntimeMetadataError(route: string): Error {
export function createNavigationMetadataError(route: string): Error {
// TODO(cache-stages): docs link
return new Error(
`Route "${route}": Next.js encountered \`unstable_navigation()\` in \`generateMetadata()\`.\n\n` +
`This route's metadata is blocked, but the rest of its content can be prefetched. \`unstable_navigation()\` called in \`generateMetadata()\` prevents it from being prefetched.\n\n` +
`Route "${route}": Next.js encountered \`navigation()\` in \`generateMetadata()\`.\n\n` +
`This route's metadata is blocked, but the rest of its content can be prefetched. \`navigation()\` called in \`generateMetadata()\` prevents it from being prefetched.\n\n` +
`Ways to fix this:\n` +
` - [static] Use a static metadata export instead of \`generateMetadata()\`\n` +
` - [dynamic] Render a marker component that calls \`await connection()\` inside \`<Suspense>\` on the page\n\n` +
......@@ -154,8 +154,8 @@ export function createRuntimeViewportError(route: string): Error {
export function createNavigationViewportError(route: string): Error {
// TODO(cache-stages): docs link
return new Error(
`Route "${route}": Next.js encountered \`unstable_navigation()\` in \`generateViewport()\`.\n\n` +
`\`unstable_navigation()\` in \`generateViewport()\` prevents creating a shell, leading to a slower user experience.\n\n` +
`Route "${route}": Next.js encountered \`navigation()\` in \`generateViewport()\`.\n\n` +
`\`navigation()\` in \`generateViewport()\` prevents creating a shell, leading to a slower user experience.\n\n` +
`Ways to fix this:\n` +
` - [static] Use a static viewport export instead of \`generateViewport()\`\n` +
` - [block] Set \`export const instant = false\` to allow a blocking route\n\n` +
......
......@@ -198,7 +198,7 @@ export function makeUnknownRuntimeDataHangingPromise<T>(
/**
* Constructs a promise that never resolves, standing in for data that is only
* accessible in the prefetch, but not in the shell, e.g. `unstable_prefetch()`.
* accessible in the prefetch, but not in the shell, e.g. `prefetch()`.
* This usage does *not* indicate that a runtime request is needed,
* only that the data is not available in a shell.
*
......
......@@ -24,25 +24,25 @@ import { RenderStage } from '../app-render/staged-rendering'
* save — and no effect on the initial load of a page.
*
* Unlike `connection()`, it does not mark the subtree as request-dependent —
* content below `await unstable_prefetch()` remains fully cacheable.
* content below `await prefetch()` remains fully cacheable.
*/
export function unstable_prefetch(): Promise<void> {
export function prefetch(): Promise<void> {
const workStore = workAsyncStorage.getStore()
const workUnitStore = workUnitAsyncStorage.getStore()
if (!workStore || !workUnitStore) {
const callingExpression = 'unstable_prefetch'
const callingExpression = 'prefetch'
throwForMissingRequestStore(callingExpression)
}
if (!process.env.__NEXT_CACHE_COMPONENTS) {
throw new Error(
`Route ${workStore.route} used \`unstable_prefetch()\`, which requires Cache Components to be enabled. Learn more: https://nextjs.org/docs/app/api-reference/config/next-config-js/cacheComponents`
`Route ${workStore.route} used \`prefetch()\`, which requires Cache Components to be enabled. Learn more: https://nextjs.org/docs/app/api-reference/config/next-config-js/cacheComponents`
)
}
if (!isRequestApiAllowedInCurrentPhase(workUnitStore)) {
throw new Error(
`Route ${workStore.route} used \`unstable_prefetch()\` inside \`after()\` while rendering. The \`unstable_prefetch()\` function is used to indicate the subsequent code must not run in the app shell, but \`after()\` executes after the request, so this function is not allowed in this scope. See more info here: https://nextjs.org/docs/app/api-reference/functions/after`
`Route ${workStore.route} used \`prefetch()\` inside \`after()\` while rendering. The \`prefetch()\` function is used to indicate the subsequent code must not run in the app shell, but \`after()\` executes after the request, so this function is not allowed in this scope. See more info here: https://nextjs.org/docs/app/api-reference/functions/after`
)
}
......@@ -54,13 +54,13 @@ export function unstable_prefetch(): Promise<void> {
const { stagedRendering } = workUnitStore
if (!stagedRendering) {
// Prospective prerender
// `unstable_prefetch()` will resolve in the final prerender, so resolve it here as well.
// `prefetch()` will resolve in the final prerender, so resolve it here as well.
return Promise.resolve(undefined)
} else {
// Final prerender
return stagedRendering.delayUntilStage(
RENDER_STAGES_BY_DATA_KIND.staticLinkData,
'unstable_prefetch',
'prefetch',
undefined
)
}
......@@ -80,7 +80,7 @@ export function unstable_prefetch(): Promise<void> {
return makePrefetchHangingPromise(
workUnitStore.renderSignal,
workStore.route,
'`unstable_prefetch()`'
'`prefetch()`'
)
} else {
return Promise.resolve(undefined)
......@@ -89,7 +89,7 @@ export function unstable_prefetch(): Promise<void> {
// Final prerender
return stagedRendering.delayUntilStage(
prefetchStage,
'unstable_prefetch',
'prefetch',
undefined
)
}
......@@ -98,51 +98,47 @@ export function unstable_prefetch(): Promise<void> {
const { stagedRendering } = workUnitStore
if (stagedRendering) {
// We can either recover a static shell or a runtime shell, but not both.
trackIncompatibleShellContent(workUnitStore, '`unstable_prefetch()`')
trackIncompatibleShellContent(workUnitStore, '`prefetch()`')
const stage = workUnitStore.needsRuntimeShell
? RENDER_STAGES_BY_DATA_KIND.runtimeLinkData // Match the timing of 'prerender-runtime'.
: RENDER_STAGES_BY_DATA_KIND.staticLinkData // Match the timing of 'prerender'.
return stagedRendering.delayUntilStage(
stage,
'unstable_prefetch',
undefined
)
return stagedRendering.delayUntilStage(stage, 'prefetch', undefined)
}
return Promise.resolve(undefined)
}
case 'cache': {
const error = new Error(
`Route ${workStore.route} used \`unstable_prefetch()\` inside "use cache". This is not currently supported. Instead, move the "use cache" directive to a function that's called below \`await unstable_prefetch()\`, so that the cached content is deferred to the prefetch without caching the stage boundary itself. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache`
`Route ${workStore.route} used \`prefetch()\` inside "use cache". This is not currently supported. Instead, move the "use cache" directive to a function that's called below \`await prefetch()\`, so that the cached content is deferred to the prefetch without caching the stage boundary itself. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache`
)
Error.captureStackTrace(error, unstable_prefetch)
Error.captureStackTrace(error, prefetch)
applyOwnerStack(error)
workStore.invalidDynamicUsageError ??= error
throw error
}
case 'private-cache': {
const error = new Error(
`Route ${workStore.route} used \`unstable_prefetch()\` inside "use cache: private". This is not currently supported. Instead, move the "use cache" directive to a function that's called below \`await unstable_prefetch()\`, so that the cached content is deferred to the prefetch without caching the stage boundary itself. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache`
`Route ${workStore.route} used \`prefetch()\` inside "use cache: private". This is not currently supported. Instead, move the "use cache" directive to a function that's called below \`await prefetch()\`, so that the cached content is deferred to the prefetch without caching the stage boundary itself. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache`
)
Error.captureStackTrace(error, unstable_prefetch)
Error.captureStackTrace(error, prefetch)
applyOwnerStack(error)
workStore.invalidDynamicUsageError ??= error
throw error
}
case 'unstable-cache': {
throw new Error(
`Route ${workStore.route} used \`unstable_prefetch()\` inside a function cached with \`unstable_cache()\`. The \`unstable_prefetch()\` function is used to indicate the subsequent code must not run in the app shell, but \`unstable_cache()\` caches must be able to be produced before a prefetch, so this function is not allowed in this scope. See more info here: https://nextjs.org/docs/app/api-reference/functions/unstable_cache`
`Route ${workStore.route} used \`prefetch()\` inside a function cached with \`unstable_cache()\`. The \`prefetch()\` function is used to indicate the subsequent code must not run in the app shell, but \`unstable_cache()\` caches must be able to be produced before a prefetch, so this function is not allowed in this scope. See more info here: https://nextjs.org/docs/app/api-reference/functions/unstable_cache`
)
}
case 'build-time-generator': {
throw new Error(
`Route ${workStore.route} used \`unstable_prefetch()\` inside \`${workUnitStore.functionName}\`. This is not supported because \`${workUnitStore.functionName}\` runs at build time without a prefetch. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context`
`Route ${workStore.route} used \`prefetch()\` inside \`${workUnitStore.functionName}\`. This is not supported because \`${workUnitStore.functionName}\` runs at build time without a prefetch. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context`
)
}
case 'prerender-client':
case 'validation-client': {
const exportName = '`unstable_prefetch`'
const exportName = '`prefetch`'
throw new InvariantError(
`${exportName} must not be used within a Client Component. Next.js should be preventing ${exportName} from being included in Client Components statically, but did not in this case.`
)
......@@ -151,7 +147,7 @@ export function unstable_prefetch(): Promise<void> {
// NOTE: Should not be reachable, because we don't use this mode in cacheComponents,
// which we require at the top
throw new Error(
`Route ${workStore.route} used \`unstable_prefetch()\`, which requires Cache Components to be enabled. Learn more: https://nextjs.org/docs/app/api-reference/config/next-config-js/cacheComponents`
`Route ${workStore.route} used \`prefetch()\`, which requires Cache Components to be enabled. Learn more: https://nextjs.org/docs/app/api-reference/config/next-config-js/cacheComponents`
)
}
......@@ -166,7 +162,7 @@ export function unstable_prefetch(): Promise<void> {
* This function allows you to indicate that the subsequent code should be
* deferred to the actual navigation instead of rendering during a runtime
* prefetch. Runtime prefetches are rendered per-user, per-link, so deferring
* content below `await unstable_navigation()` saves that per-request
* content below `await navigation()` saves that per-request
* rendering cost.
*
* It has no effect during static prerendering — static output is computed
......@@ -174,25 +170,25 @@ export function unstable_prefetch(): Promise<void> {
* save — and no effect on the initial load of a page.
*
* Unlike `connection()`, it does not mark the subtree as request-dependent —
* content below `await unstable_navigation()` remains fully cacheable.
* content below `await navigation()` remains fully cacheable.
*/
export function unstable_navigation(): Promise<void> {
export function navigation(): Promise<void> {
const workStore = workAsyncStorage.getStore()
const workUnitStore = workUnitAsyncStorage.getStore()
if (!workStore || !workUnitStore) {
const callingExpression = 'unstable_navigation'
const callingExpression = 'navigation'
throwForMissingRequestStore(callingExpression)
}
if (!process.env.__NEXT_CACHE_COMPONENTS) {
throw new Error(
`Route ${workStore.route} used \`unstable_navigation()\`, which requires Cache Components to be enabled. Learn more: https://nextjs.org/docs/app/api-reference/config/next-config-js/cacheComponents`
`Route ${workStore.route} used \`navigation()\`, which requires Cache Components to be enabled. Learn more: https://nextjs.org/docs/app/api-reference/config/next-config-js/cacheComponents`
)
}
if (!isRequestApiAllowedInCurrentPhase(workUnitStore)) {
throw new Error(
`Route ${workStore.route} used \`unstable_navigation()\` inside \`after()\` while rendering. The \`unstable_navigation()\` function is used to indicate the subsequent code must only run during an actual navigation, but \`after()\` executes after the request, so this function is not allowed in this scope. See more info here: https://nextjs.org/docs/app/api-reference/functions/after`
`Route ${workStore.route} used \`navigation()\` inside \`after()\` while rendering. The \`navigation()\` function is used to indicate the subsequent code must only run during an actual navigation, but \`after()\` executes after the request, so this function is not allowed in this scope. See more info here: https://nextjs.org/docs/app/api-reference/functions/after`
)
}
......@@ -203,17 +199,17 @@ export function unstable_navigation(): Promise<void> {
// deferring the content — it's deliberately included in the static
// output (and thus in static prefetches).
// However, it's excluded from the shell, and has to be separated from
// unstable_prefetch(), so we have to delay it.
// prefetch(), so we have to delay it.
const { stagedRendering } = workUnitStore
if (!stagedRendering) {
// Prospective prerender
// `unstable_navigation()` will resolve in the final prerender, so resolve it here as well.
// `navigation()` will resolve in the final prerender, so resolve it here as well.
return Promise.resolve(undefined)
} else {
// Final prerender
return stagedRendering.delayUntilStage(
RenderStage.NavigationStatic,
'unstable_navigation',
'navigation',
undefined
)
}
......@@ -233,7 +229,7 @@ export function unstable_navigation(): Promise<void> {
return makeUntrackedHangingPromise(
workUnitStore.renderSignal,
workStore.route,
'`unstable_navigation()`'
'`navigation()`'
)
} else {
return Promise.resolve(undefined)
......@@ -242,7 +238,7 @@ export function unstable_navigation(): Promise<void> {
// Final prerender
return stagedRendering.delayUntilStage(
navigationStage,
'unstable_navigation',
'navigation',
undefined
)
}
......@@ -251,51 +247,47 @@ export function unstable_navigation(): Promise<void> {
const { stagedRendering } = workUnitStore
if (stagedRendering) {
// We can either recover a static shell or a runtime shell, but not both.
trackIncompatibleShellContent(workUnitStore, '`unstable_navigation()`')
trackIncompatibleShellContent(workUnitStore, '`navigation()`')
const stage = workUnitStore.needsRuntimeShell
? RenderStage.NavigationRuntime // Match the timing of 'prerender-runtime'.
: RenderStage.NavigationStatic // Match the timing of 'prerender'.
return stagedRendering.delayUntilStage(
stage,
'unstable_navigation',
undefined
)
return stagedRendering.delayUntilStage(stage, 'navigation', undefined)
}
return Promise.resolve(undefined)
}
case 'cache': {
const error = new Error(
`Route ${workStore.route} used \`unstable_navigation()\` inside "use cache". This is not currently supported. Instead, move the "use cache" directive to a function that's called below \`await unstable_navigation()\`, so that the cached content is deferred to the navigation without caching the stage boundary itself. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache`
`Route ${workStore.route} used \`navigation()\` inside "use cache". This is not currently supported. Instead, move the "use cache" directive to a function that's called below \`await navigation()\`, so that the cached content is deferred to the navigation without caching the stage boundary itself. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache`
)
Error.captureStackTrace(error, unstable_navigation)
Error.captureStackTrace(error, navigation)
applyOwnerStack(error)
workStore.invalidDynamicUsageError ??= error
throw error
}
case 'private-cache': {
const error = new Error(
`Route ${workStore.route} used \`unstable_navigation()\` inside "use cache: private". This is not currently supported. Instead, move the "use cache" directive to a function that's called below \`await unstable_navigation()\`, so that the cached content is deferred to the navigation without caching the stage boundary itself. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache`
`Route ${workStore.route} used \`navigation()\` inside "use cache: private". This is not currently supported. Instead, move the "use cache" directive to a function that's called below \`await navigation()\`, so that the cached content is deferred to the navigation without caching the stage boundary itself. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache`
)
Error.captureStackTrace(error, unstable_navigation)
Error.captureStackTrace(error, navigation)
applyOwnerStack(error)
workStore.invalidDynamicUsageError ??= error
throw error
}
case 'unstable-cache': {
throw new Error(
`Route ${workStore.route} used \`unstable_navigation()\` inside a function cached with \`unstable_cache()\`. The \`unstable_navigation()\` function is used to indicate the subsequent code must only run during an actual navigation, but \`unstable_cache()\` caches must be able to be produced before a navigation, so this function is not allowed in this scope. See more info here: https://nextjs.org/docs/app/api-reference/functions/unstable_cache`
`Route ${workStore.route} used \`navigation()\` inside a function cached with \`unstable_cache()\`. The \`navigation()\` function is used to indicate the subsequent code must only run during an actual navigation, but \`unstable_cache()\` caches must be able to be produced before a navigation, so this function is not allowed in this scope. See more info here: https://nextjs.org/docs/app/api-reference/functions/unstable_cache`
)
}
case 'build-time-generator': {
throw new Error(
`Route ${workStore.route} used \`unstable_navigation()\` inside \`${workUnitStore.functionName}\`. This is not supported because \`${workUnitStore.functionName}\` runs at build time without a navigation. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context`
`Route ${workStore.route} used \`navigation()\` inside \`${workUnitStore.functionName}\`. This is not supported because \`${workUnitStore.functionName}\` runs at build time without a navigation. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context`
)
}
case 'prerender-client':
case 'validation-client': {
const exportName = '`unstable_navigation`'
const exportName = '`navigation`'
throw new InvariantError(
`${exportName} must not be used within a Client Component. Next.js should be preventing ${exportName} from being included in Client Components statically, but did not in this case.`
)
......@@ -304,7 +296,7 @@ export function unstable_navigation(): Promise<void> {
// NOTE: Should not be reachable, because we don't use this mode in cacheComponents,
// which we require at the top
throw new Error(
`Route ${workStore.route} used \`unstable_navigation()\`, which requires Cache Components to be enabled. Learn more: https://nextjs.org/docs/app/api-reference/config/next-config-js/cacheComponents`
`Route ${workStore.route} used \`navigation()\`, which requires Cache Components to be enabled. Learn more: https://nextjs.org/docs/app/api-reference/config/next-config-js/cacheComponents`
)
}
......
......@@ -138,16 +138,16 @@ follow the static-shell documentation used by
authorization behavior. Change only what the selected contract requires.
When reusable UI should wait for navigation, follow the
[`unstable_navigation()`](https://nextjs.org/docs/app/api-reference/functions/navigation)
[`navigation()`](https://nextjs.org/docs/app/api-reference/functions/navigation)
reference, including its comparison with `connection()`. Then verify both
properties independently. The `instant()` assertion proves that the UI is
absent from the prefetch; it does not prove that the underlying work stayed
reusable. Verify that reusable work remains cached below the stage boundary.
When the contract needs an explicit runtime stage, follow the API references
for [`unstable_prefetch()`](https://nextjs.org/docs/app/api-reference/functions/prefetch)
for [`prefetch()`](https://nextjs.org/docs/app/api-reference/functions/prefetch)
and
[`unstable_navigation()`](https://nextjs.org/docs/app/api-reference/functions/navigation).
[`navigation()`](https://nextjs.org/docs/app/api-reference/functions/navigation).
Work one accepted navigation to GREEN before moving to another. Do not create
an app-wide Link or cache abstraction from a single case.
......
import { cookies, headers } from 'next/headers'
import { CachedData } from '../../data-fetching'
import { connection } from 'next/server'
import {
unstable_navigation as navigation,
unstable_prefetch,
} from 'next/cache'
import { navigation, prefetch as prefetchStage } from 'next/cache'
import { Suspense } from 'react'
export const instant = true
......@@ -26,7 +23,7 @@ export default function Page({ params, searchParams }) {
<LogAfter label="headers" api={() => headers()} />
<LogAfter label="params" api={() => params} />
<LogAfter label="searchParams" api={() => searchParams} />
<LogAfter label="prefetch" api={() => unstable_prefetch()} />
<LogAfter label="prefetch" api={() => prefetchStage()} />
<LogAfter label="navigation" api={() => navigation()} />
{/* Dynamic */}
......
import { cookies, headers } from 'next/headers'
import { CachedData } from '../../data-fetching'
import { connection } from 'next/server'
import {
unstable_navigation as navigation,
unstable_prefetch,
} from 'next/cache'
import { navigation, prefetch } from 'next/cache'
import { Suspense } from 'react'
const CACHE_KEY = __dirname + '/__PAGE__'
......@@ -23,7 +20,7 @@ export default function Page({ params, searchParams }) {
<LogAfter label="headers" api={() => headers()} />
<LogAfter label="params" api={() => params} />
<LogAfter label="searchParams" api={() => searchParams} />
<LogAfter label="prefetch" api={() => unstable_prefetch()} />
<LogAfter label="prefetch" api={() => prefetch()} />
<LogAfter label="navigation" api={() => navigation()} />
{/* Dynamic */}
......
import { unstable_navigation } from 'next/cache'
import { navigation } from 'next/cache'
import { Suspense } from 'react'
import UncachedTimePage from '../uncached-time/page'
async function Content() {
// The navigation stage defers this subtree past the initial Flight rows. The
// private cache in UncachedTimePage still resolves before the dynamic stage.
await unstable_navigation()
await navigation()
return <UncachedTimePage />
}
......
import { unstable_navigation } from 'next/cache'
import { navigation } from 'next/cache'
// NOTE: the page must export the following literally, we can't
// reexport them from here:
......@@ -23,6 +23,6 @@ export default async function Page() {
}
async function Navigation() {
await unstable_navigation()
await navigation()
return <div>Navigation data</div>
}
import { unstable_prefetch } from 'next/cache'
import { prefetch } from 'next/cache'
// NOTE: the page must export the following literally, we can't
// reexport them from here:
......@@ -23,6 +23,6 @@ export default async function Page() {
}
async function Prefetch() {
await unstable_prefetch()
await prefetch()
return <div>Prefetch data</div>
}
import { Instant } from 'next'
import { unstable_navigation as navigation } from 'next/cache'
import { navigation } from 'next/cache'
export const instant: Instant = {
level: 'experimental-error',
......
import { Instant } from 'next'
import { unstable_prefetch } from 'next/cache'
import { prefetch as prefetchStage } from 'next/cache'
export const instant: Instant = {
level: 'experimental-error',
......@@ -20,6 +20,6 @@ export default async function Page() {
}
async function PrefetchContent() {
await unstable_prefetch()
await prefetchStage()
return <div>{`Prefetch content`}</div>
}
import { Instant } from 'next'
import { unstable_navigation as navigation } from 'next/cache'
import { navigation } from 'next/cache'
import { Suspense } from 'react'
export const instant: Instant = {
......
import { Instant } from 'next'
import { unstable_prefetch } from 'next/cache'
import { prefetch as prefetchStage } from 'next/cache'
import { Suspense } from 'react'
export const instant: Instant = {
......@@ -23,6 +23,6 @@ export default async function Page() {
}
async function PrefetchContent() {
await unstable_prefetch()
await prefetchStage()
return <div>{`Prefetch content`}</div>
}
import { Instant } from 'next'
import { unstable_navigation as navigation } from 'next/cache'
import { navigation } from 'next/cache'
export const instant: Instant = {
level: 'experimental-error',
......
import { Instant } from 'next'
import { unstable_prefetch } from 'next/cache'
import { prefetch } from 'next/cache'
export const instant: Instant = {
level: 'experimental-error',
......@@ -18,6 +18,6 @@ export default async function Page() {
}
async function PrefetchContent() {
await unstable_prefetch()
await prefetch()
return <div>{`Prefetch content`}</div>
}
import { unstable_navigation as navigation } from 'next/cache'
import { navigation } from 'next/cache'
import { Suspense } from 'react'
export const instant = { level: 'experimental-error' }
......
import { unstable_prefetch } from 'next/cache'
import { prefetch } from 'next/cache'
import { Suspense } from 'react'
export const instant = { level: 'experimental-error' }
......@@ -23,6 +23,6 @@ export default async function Page() {
}
async function SyncIOAfterPrefetch() {
await unstable_prefetch()
await prefetch()
return Date.now()
}
......@@ -12,7 +12,7 @@ const partialPrefetching = !!process.env.__NEXT_PARTIAL_PREFETCHING
const INSTANT_INSIGHT_PATTERNS = {
urlData: /Next\.js encountered URL data/,
navigation: /Next\.js encountered `?unstable_navigation\(\)`?/,
navigation: /Next\.js encountered `?navigation\(\)`?/,
runtimeData: /Next\.js encountered runtime data/,
uncachedData: /Next\.js encountered uncached data/,
}
......@@ -1090,7 +1090,7 @@ export function registerHeadAndReportingTests(
],
},
],
"description": "Next.js encountered unstable_navigation() outside of Suspense.",
"description": "Next.js encountered navigation() outside of Suspense.",
"environmentLabel": "Server",
"label": "Instant",
"source": "app/shells/(default)/invalid-navigation-without-suspense/page.tsx (23:19) @ NavigationContent
......@@ -1108,9 +1108,9 @@ export function registerHeadAndReportingTests(
)
expect(extractBuildValidationError(result.cliOutput))
.toMatchInlineSnapshot(`
"Error: Route "/shells/invalid-navigation-without-suspense": Next.js encountered \`unstable_navigation()\` during prerendering or a navigation.
"Error: Route "/shells/invalid-navigation-without-suspense": Next.js encountered \`navigation()\` during prerendering or a navigation.
\`unstable_navigation()\` called outside of \`<Suspense>\` may prevent the navigation from being instant, leading to a slower user experience.
\`navigation()\` called outside of \`<Suspense>\` may prevent the navigation from being instant, leading to a slower user experience.
Ways to fix this:
- [stream] Provide a placeholder with \`<Suspense fallback={...}>\` around the data access
......@@ -1166,11 +1166,11 @@ export function registerHeadAndReportingTests(
"description": "Next.js encountered URL data outside of Suspense.",
"environmentLabel": "Server",
"label": "Instant",
"source": "app/shells/(default)/invalid-prefetch-without-suspense/page.tsx (23:26) @ PrefetchContent
> 23 | await unstable_prefetch()
| ^",
"source": "app/shells/(default)/invalid-prefetch-without-suspense/page.tsx (23:22) @ PrefetchContent
> 23 | await prefetchStage()
| ^",
"stack": [
"PrefetchContent app/shells/(default)/invalid-prefetch-without-suspense/page.tsx (23:26)",
"PrefetchContent app/shells/(default)/invalid-prefetch-without-suspense/page.tsx (23:22)",
"Page app/shells/(default)/invalid-prefetch-without-suspense/page.tsx (17:7)",
],
}
......@@ -1741,11 +1741,11 @@ export function registerHeadAndReportingTests(
"description": "Next.js encountered URL data outside of Suspense.",
"environmentLabel": "Server",
"label": "Instant",
"source": "app/shells/(default)/ensure-static/_base/prefetch-without-suspense/page.base.tsx (26:26) @ Prefetch
> 26 | await unstable_prefetch()
| ^",
"source": "app/shells/(default)/ensure-static/_base/prefetch-without-suspense/page.base.tsx (26:17) @ Prefetch
> 26 | await prefetch()
| ^",
"stack": [
"Prefetch app/shells/(default)/ensure-static/_base/prefetch-without-suspense/page.base.tsx (26:26)",
"Prefetch app/shells/(default)/ensure-static/_base/prefetch-without-suspense/page.base.tsx (26:17)",
"Page app/shells/(default)/ensure-static/_base/prefetch-without-suspense/page.base.tsx (20:7)",
],
}
......@@ -1802,11 +1802,11 @@ export function registerHeadAndReportingTests(
"description": "Next.js encountered URL data outside of Suspense.",
"environmentLabel": "Server",
"label": "Instant",
"source": "app/shells/(default)/ensure-static/_base/prefetch-without-suspense/page.base.tsx (26:26) @ Prefetch
> 26 | await unstable_prefetch()
| ^",
"source": "app/shells/(default)/ensure-static/_base/prefetch-without-suspense/page.base.tsx (26:17) @ Prefetch
> 26 | await prefetch()
| ^",
"stack": [
"Prefetch app/shells/(default)/ensure-static/_base/prefetch-without-suspense/page.base.tsx (26:26)",
"Prefetch app/shells/(default)/ensure-static/_base/prefetch-without-suspense/page.base.tsx (26:17)",
"Page app/shells/(default)/ensure-static/_base/prefetch-without-suspense/page.base.tsx (20:7)",
],
}
......@@ -1863,11 +1863,11 @@ export function registerHeadAndReportingTests(
"description": "Next.js encountered URL data outside of Suspense.",
"environmentLabel": "Server",
"label": "Instant",
"source": "app/shells/(default)/ensure-static/_base/prefetch-without-suspense/page.base.tsx (26:26) @ Prefetch
> 26 | await unstable_prefetch()
| ^",
"source": "app/shells/(default)/ensure-static/_base/prefetch-without-suspense/page.base.tsx (26:17) @ Prefetch
> 26 | await prefetch()
| ^",
"stack": [
"Prefetch app/shells/(default)/ensure-static/_base/prefetch-without-suspense/page.base.tsx (26:26)",
"Prefetch app/shells/(default)/ensure-static/_base/prefetch-without-suspense/page.base.tsx (26:17)",
"Page app/shells/(default)/ensure-static/_base/prefetch-without-suspense/page.base.tsx (20:7)",
],
}
......@@ -1991,14 +1991,14 @@ export function registerHeadAndReportingTests(
],
},
],
"description": "Next.js encountered unstable_navigation() outside of Suspense.",
"description": "Next.js encountered navigation() outside of Suspense.",
"environmentLabel": "Server",
"label": "Instant",
"source": "app/shells/(default)/ensure-static/_base/navigation-without-suspense/page.base.tsx (26:28) @ Navigation
> 26 | await unstable_navigation()
| ^",
"source": "app/shells/(default)/ensure-static/_base/navigation-without-suspense/page.base.tsx (26:19) @ Navigation
> 26 | await navigation()
| ^",
"stack": [
"Navigation app/shells/(default)/ensure-static/_base/navigation-without-suspense/page.base.tsx (26:28)",
"Navigation app/shells/(default)/ensure-static/_base/navigation-without-suspense/page.base.tsx (26:19)",
"Page app/shells/(default)/ensure-static/_base/navigation-without-suspense/page.base.tsx (20:7)",
],
}
......@@ -2010,9 +2010,9 @@ export function registerHeadAndReportingTests(
const error = extractBuildValidationError(result.cliOutput)
expect(error).toMatch(errorPattern)
expect(error).toMatchInlineSnapshot(`
"Error: Route "/shells/ensure-static/false/navigation-without-suspense": Next.js encountered \`unstable_navigation()\` during prerendering or a navigation.
"Error: Route "/shells/ensure-static/false/navigation-without-suspense": Next.js encountered \`navigation()\` during prerendering or a navigation.
\`unstable_navigation()\` called outside of \`<Suspense>\` may prevent the navigation from being instant, leading to a slower user experience.
\`navigation()\` called outside of \`<Suspense>\` may prevent the navigation from being instant, leading to a slower user experience.
Ways to fix this:
- [stream] Provide a placeholder with \`<Suspense fallback={...}>\` around the data access
......@@ -2052,14 +2052,14 @@ export function registerHeadAndReportingTests(
],
},
],
"description": "Next.js encountered unstable_navigation() outside of Suspense.",
"description": "Next.js encountered navigation() outside of Suspense.",
"environmentLabel": "Server",
"label": "Instant",
"source": "app/shells/(default)/ensure-static/_base/navigation-without-suspense/page.base.tsx (26:28) @ Navigation
> 26 | await unstable_navigation()
| ^",
"source": "app/shells/(default)/ensure-static/_base/navigation-without-suspense/page.base.tsx (26:19) @ Navigation
> 26 | await navigation()
| ^",
"stack": [
"Navigation app/shells/(default)/ensure-static/_base/navigation-without-suspense/page.base.tsx (26:28)",
"Navigation app/shells/(default)/ensure-static/_base/navigation-without-suspense/page.base.tsx (26:19)",
"Page app/shells/(default)/ensure-static/_base/navigation-without-suspense/page.base.tsx (20:7)",
],
}
......@@ -2071,9 +2071,9 @@ export function registerHeadAndReportingTests(
const error = extractBuildValidationError(result.cliOutput)
expect(error).toMatch(errorPattern)
expect(error).toMatchInlineSnapshot(`
"Error: Route "/shells/ensure-static/shell/navigation-without-suspense": Next.js encountered \`unstable_navigation()\` during prerendering or a navigation.
"Error: Route "/shells/ensure-static/shell/navigation-without-suspense": Next.js encountered \`navigation()\` during prerendering or a navigation.
\`unstable_navigation()\` called outside of \`<Suspense>\` may prevent the navigation from being instant, leading to a slower user experience.
\`navigation()\` called outside of \`<Suspense>\` may prevent the navigation from being instant, leading to a slower user experience.
Ways to fix this:
- [stream] Provide a placeholder with \`<Suspense fallback={...}>\` around the data access
......@@ -2113,14 +2113,14 @@ export function registerHeadAndReportingTests(
],
},
],
"description": "Next.js encountered unstable_navigation() outside of Suspense.",
"description": "Next.js encountered navigation() outside of Suspense.",
"environmentLabel": "Server",
"label": "Instant",
"source": "app/shells/(default)/ensure-static/_base/navigation-without-suspense/page.base.tsx (26:28) @ Navigation
> 26 | await unstable_navigation()
| ^",
"source": "app/shells/(default)/ensure-static/_base/navigation-without-suspense/page.base.tsx (26:19) @ Navigation
> 26 | await navigation()
| ^",
"stack": [
"Navigation app/shells/(default)/ensure-static/_base/navigation-without-suspense/page.base.tsx (26:28)",
"Navigation app/shells/(default)/ensure-static/_base/navigation-without-suspense/page.base.tsx (26:19)",
"Page app/shells/(default)/ensure-static/_base/navigation-without-suspense/page.base.tsx (20:7)",
],
}
......@@ -2132,9 +2132,9 @@ export function registerHeadAndReportingTests(
const error = extractBuildValidationError(result.cliOutput)
expect(error).toMatch(errorPattern)
expect(error).toMatchInlineSnapshot(`
"Error: Route "/shells/ensure-static/prefetch/navigation-without-suspense": Next.js encountered \`unstable_navigation()\` during prerendering or a navigation.
"Error: Route "/shells/ensure-static/prefetch/navigation-without-suspense": Next.js encountered \`navigation()\` during prerendering or a navigation.
\`unstable_navigation()\` called outside of \`<Suspense>\` may prevent the navigation from being instant, leading to a slower user experience.
\`navigation()\` called outside of \`<Suspense>\` may prevent the navigation from being instant, leading to a slower user experience.
Ways to fix this:
- [stream] Provide a placeholder with \`<Suspense fallback={...}>\` around the data access
......
......@@ -181,7 +181,7 @@ export function registerSyncIoAndBlockingTests(
Learn more: https://nextjs.org/docs/messages/blocking-prerender-current-time
at a (app/suspense-in-root/sync-io/sync-io-after-prefetch/page.tsx:27:15)
25 | async function SyncIOAfterPrefetch() {
26 | await unstable_prefetch()
26 | await prefetch()
> 27 | return Date.now()
| ^
28 | }
......
import { cookies, headers } from 'next/headers'
import { connection } from 'next/server'
import {
unstable_navigation as navigation,
unstable_prefetch,
} from 'next/cache'
import { navigation, prefetch } from 'next/cache'
import { Suspense } from 'react'
// Note: intentionally no `export const prefetch` and no `instant` config. This
......@@ -89,6 +86,6 @@ async function NavigationContent() {
}
async function PrefetchContent() {
await unstable_prefetch()
await prefetch()
return <p>Prefetch content</p>
}
import { getCachedValue, CookieData } from '../../../cached-value'
import { Suspense } from 'react'
import { connection } from 'next/server'
import { unstable_prefetch } from 'next/cache'
import { prefetch } from 'next/cache'
export default async function Page() {
const cachedValue = await getCachedValue()
......@@ -42,7 +42,7 @@ export default async function Page() {
}
async function PrefetchOnly({ children }) {
await unstable_prefetch()
await prefetch()
return children
}
......
import { getCachedValue, CookieData } from '../../../cached-value'
import { Suspense } from 'react'
import { connection } from 'next/server'
import { unstable_prefetch } from 'next/cache'
import { prefetch } from 'next/cache'
export default async function Page() {
const cachedValue = await getCachedValue()
......@@ -42,7 +42,7 @@ export default async function Page() {
}
async function PrefetchOnly({ children }) {
await unstable_prefetch()
await prefetch()
return children
}
......
import { ConditionalCookies } from '../../cached-value'
import { Suspense } from 'react'
import { connection } from 'next/server'
import { unstable_prefetch } from 'next/cache'
import { prefetch } from 'next/cache'
export default async function Page() {
return (
......@@ -27,7 +27,7 @@ export default async function Page() {
}
async function PrefetchOnly({ children }) {
await unstable_prefetch()
await prefetch()
return children
}
......
import { ConditionalCookies } from '../../../cached-value'
import { Suspense } from 'react'
import { connection } from 'next/server'
import { unstable_prefetch } from 'next/cache'
import { prefetch } from 'next/cache'
export default async function Page() {
return (
......@@ -32,6 +32,6 @@ async function DynamicData() {
return <div id="dynamic-data">Dynamic data</div>
}
async function PrefetchData() {
await unstable_prefetch()
await prefetch()
return <div id="prefetch-data">Prefetch data</div>
}
import { ConditionalCookies } from '../../../cached-value'
import { Suspense } from 'react'
import { unstable_prefetch } from 'next/cache'
import { prefetch } from 'next/cache'
export default async function Page() {
return (
......@@ -22,6 +22,6 @@ export default async function Page() {
}
async function PrefetchData() {
await unstable_prefetch()
await prefetch()
return <div id="prefetch-data">Prefetch data</div>
}
import { cacheTag, revalidateTag, unstable_prefetch } from 'next/cache'
import { cacheTag, revalidateTag, prefetch } from 'next/cache'
import * as fs from 'node:fs'
import { Suspense } from 'react'
......@@ -92,7 +92,7 @@ async function CookieDataImpl({ label }: { label?: string }) {
}
async function RuntimePrefetchData() {
await unstable_prefetch()
await prefetch()
return (
<div id="cookies-runtime-prefetch-data">
Runtime prefetch data (behind cookies)
......
import { Suspense } from 'react'
import { unstable_navigation as navigation } from 'next/cache'
import { navigation } from 'next/cache'
import { cookies } from 'next/headers'
import { connection } from 'next/server'
......
import { Suspense } from 'react'
import { unstable_prefetch } from 'next/cache'
import { prefetch as prefetchStage } from 'next/cache'
import { cookies } from 'next/headers'
import { connection } from 'next/server'
......@@ -24,7 +24,7 @@ export default async function Page({ params }: { params: Promise<Params> }) {
async function PrefetchData() {
await cookies() // Makes sure this page uses a runtime prefetch
await unstable_prefetch() // Exclude the contents below from runtime app shells
await prefetchStage() // Exclude the contents below from runtime app shells
return <div id="prefetch-content">Prefetch content</div>
}
......
import { Suspense } from 'react'
import { unstable_navigation as navigation } from 'next/cache'
import { navigation } from 'next/cache'
import { connection } from 'next/server'
export async function generateStaticParams() {
......
import { Suspense } from 'react'
import { unstable_prefetch } from 'next/cache'
import { prefetch as prefetchStage } from 'next/cache'
import { connection } from 'next/server'
export async function generateStaticParams() {
......@@ -24,7 +24,7 @@ export default async function Page({ params }: { params: Promise<Params> }) {
}
async function PrefetchData() {
await unstable_prefetch() // Exclude the contents below from the shell
await prefetchStage() // Exclude the contents below from the shell
return <div id="prefetch-content">Prefetch content</div>
}
......
import { unstable_navigation } from 'next/cache'
import { navigation } from 'next/cache'
import { cookies } from 'next/headers'
import { Suspense } from 'react'
......@@ -66,6 +66,6 @@ async function ConditionalCookiesUse({ slug }: { slug: string }) {
}
async function NavigationContent({ slug }: { slug: string }) {
await unstable_navigation()
await navigation()
return <div>{`Navigation content on ${slug}`}</div>
}
import { unstable_prefetch } from 'next/cache'
import { prefetch } from 'next/cache'
import { Suspense } from 'react'
/**
......@@ -35,6 +35,6 @@ export function PrefetchContent({ text }: { text: string }) {
}
async function Inner({ text }: { text: string }) {
await unstable_prefetch()
await prefetch()
return <div id="prefetch-content">{text}</div>
}
import { Suspense } from 'react'
import {
unstable_navigation as navigation,
unstable_prefetch,
} from 'next/cache'
import { navigation, prefetch } from 'next/cache'
type Params = { slug: string }
......@@ -53,6 +50,6 @@ async function NavigationContent() {
}
async function PrefetchContent() {
await unstable_prefetch()
await prefetch()
return <p id="prefetch-content">Prefetch content</p>
}
import { unstable_navigation as navigation } from 'next/cache'
import { navigation } from 'next/cache'
import { Suspense } from 'react'
type Props = { params: Promise<{ id: string }> }
......
import { Suspense } from 'react'
import { unstable_navigation as navigation } from 'next/cache'
import { navigation } from 'next/cache'
export default function Page() {
return (
......
import { Suspense } from 'react'
import { unstable_prefetch } from 'next/cache'
import { prefetch } from 'next/cache'
export default function Page() {
return (
......@@ -12,6 +12,6 @@ export default function Page() {
}
async function PrefetchContent() {
await unstable_prefetch()
await prefetch()
return <p id="page-content">Fully static page content (with prefetch())</p>
}
......@@ -7,7 +7,7 @@
import { cacheLife } from 'next/dist/server/use-cache/cache-life'
import { cookies, headers } from 'next/headers'
import { unstable_navigation as navigation } from 'next/cache'
import { navigation } from 'next/cache'
import { Suspense } from 'react'
export default async function Page() {
......
// A page that calls cookies and headers after awaiting `unstable_prefetch()`.
// A page that calls cookies and headers after awaiting `prefetch()`.
// Unlike `navigation()`, `prefetch()` doesn't stop runtime-data tracking — the
// reads below it still count — so the tree hint stays unset and this route
// can't be prefetched statically.
import { cookies, headers } from 'next/headers'
import { unstable_prefetch } from 'next/cache'
import { prefetch } from 'next/cache'
import { Suspense } from 'react'
export default async function Page() {
......@@ -21,7 +21,7 @@ export default async function Page() {
}
async function Prefetch() {
await unstable_prefetch()
await prefetch()
return (
<>
......
import {
unstable_prefetch as prefetch,
unstable_navigation as navigation,
} from 'next/cache'
import { prefetch, navigation } from 'next/cache'
import { cookies } from 'next/headers'
import { Suspense } from 'react'
......
import {
unstable_prefetch as prefetch,
unstable_navigation as navigation,
} from 'next/cache'
import { prefetch, navigation } from 'next/cache'
import { cookies } from 'next/headers'
import { Suspense } from 'react'
......
import { unstable_navigation as navigation } from 'next/cache'
import { navigation } from 'next/cache'
import { cookies } from 'next/headers'
import { connection } from 'next/server'
import { Suspense } from 'react'
......
import { unstable_prefetch as prefetch } from 'next/cache'
import { prefetch } from 'next/cache'
import { cookies } from 'next/headers'
import { connection } from 'next/server'
import { Suspense } from 'react'
......
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