Unverified Commit 4b56cee3 authored by Joseph's avatar Joseph Committed by GitHub

[16.3.x] Backport docs fixes (#98317)

- docs: explain origin matching for allowedOrigins and allowedDevOrigins
(#97805)
- docs: improve discovery summaries (#97982)
- docs(skills): preserve prefetched UI during Partial Prefetching
adoption (#97712)
- docs: add layout stability guidance for videos and iframes (#98070)
- docs: document preloading with Cache Components (#97864)
- docs: note that experimental.taint taints process.env (#98145)
- docs: add API reference pages for skipProxyUrlNormalize and
skipTrailingSlashRedirect (#97967)
- docs: keep generateStaticParams during Cache Components migration
(docs part of #98209)
- docs: Remove version label from Turbopack in Pages Router (#98316)

---------
Co-authored-by: 's avatarRich Haines <hello@richardhaines.dev>
Co-authored-by: 's avatarAurora Scharff <66901228+aurorascharff@users.noreply.github.com>
parent 5568a02a
...@@ -545,23 +545,27 @@ export default async function Page({ params }) { ...@@ -545,23 +545,27 @@ export default async function Page({ params }) {
### Reusing data with `React.cache` ### Reusing data with `React.cache`
Wrap a data-fetching function in [`React.cache`](https://react.dev/reference/react/cache) so multiple components in the same request share one result instead of refetching: For data access that does not use `fetch`, such as an ORM or database query, wrap the function in [`React.cache`](https://react.dev/reference/react/cache). Multiple components can then call the function within the same request while sharing one result:
```ts filename="app/lib/user.ts" switcher ```ts filename="app/lib/user.ts" switcher
import { cache } from 'react' import { cache } from 'react'
import { db, eq, users } from '@/lib/db'
export const getUser = cache(async () => { export const getUser = cache(async (id: string) => {
const res = await fetch('https://api.example.com/user') return db.query.users.findFirst({
return res.json() where: eq(users.id, id),
})
}) })
``` ```
```js filename="app/lib/user.js" switcher ```js filename="app/lib/user.js" switcher
import { cache } from 'react' import { cache } from 'react'
import { db, eq, users } from '@/lib/db'
export const getUser = cache(async () => { export const getUser = cache(async (id) => {
const res = await fetch('https://api.example.com/user') return db.query.users.findFirst({
return res.json() where: eq(users.id, id),
})
}) })
``` ```
...@@ -571,7 +575,12 @@ Server Components can call `getUser()` directly: ...@@ -571,7 +575,12 @@ Server Components can call `getUser()` directly:
import { getUser } from '../lib/user' import { getUser } from '../lib/user'
export default async function DashboardPage() { export default async function DashboardPage() {
const user = await getUser() // Cached - same request, no duplicate fetch const user = await getUser('1')
if (!user) {
return null
}
return <h1>Dashboard for {user.name}</h1> return <h1>Dashboard for {user.name}</h1>
} }
``` ```
...@@ -580,11 +589,100 @@ export default async function DashboardPage() { ...@@ -580,11 +589,100 @@ export default async function DashboardPage() {
import { getUser } from '../lib/user' import { getUser } from '../lib/user'
export default async function DashboardPage() { export default async function DashboardPage() {
const user = await getUser() // Cached - same request, no duplicate fetch const user = await getUser('1')
if (!user) {
return null
}
return <h1>Dashboard for {user.name}</h1> return <h1>Dashboard for {user.name}</h1>
} }
``` ```
Since `getUser` is wrapped with `React.cache`, multiple calls within the same request return the same memoized result, whether called directly in Server Components or resolved via context in Client Components. Since `getUser` is wrapped with `React.cache`, calls with the same `id` within one request return the same memoized result.
> **Good to know:** [`React.cache`](https://react.dev/reference/react/cache#caveats) is scoped to the current request only. Each request gets its own memoization scope with no sharing between requests.
### Preloading data
When a component renders after other blocking work, its data request starts late even if the request inputs are already available. Preloading starts the request earlier so it can run in parallel with that work and avoid a request waterfall.
To preload data, call the data-fetching function without `await` before blocking work, then call the same function in the component that consumes the result.
The data-fetching function must deduplicate matching calls so the component can reuse the request started during preloading. Use one of the following approaches:
- For `fetch`, [identical requests are memoized automatically](/docs/app/api-reference/functions/fetch#memoization).
- For an ORM or database, wrap the data-fetching function in [`React.cache`](#reusing-data-with-reactcache).
- With Cache Components, add [`'use cache'`](/docs/app/api-reference/directives/use-cache) to the data-fetching function. If the function reads request APIs such as `cookies()` or `headers()`, use [`'use cache: private'`](/docs/app/api-reference/directives/use-cache-private).
In production, matching calls to a private Cache Function can reuse the same result within one request. This lets a component reuse a request started during preloading without storing the result in a server cache across requests.
Keep the preload function next to the component that consumes the data. This makes the dependency easier to find if you move or remove the component:
```tsx filename="app/item/[id]/item.tsx" switcher
async function getItem(id: string) {
const res = await fetch(`https://api.example.com/items/${id}`)
return res.json()
}
export const preload = (id: string) => {
void getItem(id)
}
export default async function Item({ id }: { id: string }) {
const item = await getItem(id)
return <div>{item.name}</div>
}
```
```jsx filename="app/item/[id]/item.js" switcher
async function getItem(id) {
const res = await fetch(`https://api.example.com/items/${id}`)
return res.json()
}
export const preload = (id) => {
void getItem(id)
}
export default async function Item({ id }) {
const item = await getItem(id)
return <div>{item.name}</div>
}
```
Call `preload()` before another blocking request to start loading the item earlier:
```tsx filename="app/item/[id]/page.tsx" switcher
import Item, { preload } from './item'
import { checkIsAvailable } from '@/app/lib/data'
export default async function Page({
params,
}: {
params: Promise<{ id: string }>
}) {
const { id } = await params
preload(id)
const isAvailable = await checkIsAvailable(id)
return isAvailable ? <Item id={id} /> : null
}
```
```jsx filename="app/item/[id]/page.js" switcher
import Item, { preload } from './item'
import { checkIsAvailable } from '@/app/lib/data'
export default async function Page({ params }) {
const { id } = await params
preload(id)
const isAvailable = await checkIsAvailable(id)
return isAvailable ? <Item id={id} /> : null
}
```
> **Good to know**: `React.cache` is scoped to the current request only. Each request gets its own memoization scope with no sharing between requests. The item request continues while `checkIsAvailable()` runs. If the page renders `<Item>`, the identical `fetch` call reuses the request that `preload()` started.
--- ---
title: Route Handlers title: Route Handlers
nav_title: Route Handlers nav_title: Route Handlers
description: Learn how to use Route Handlers description: Create custom request handlers with Next.js Route Handlers using the Web Request and Response APIs.
related: related:
title: API Reference title: API Reference
description: Learn more about Route Handlers description: Learn more about Route Handlers
......
--- ---
title: Proxy title: Proxy
nav_title: Proxy nav_title: Proxy
description: Learn how to use Proxy description: Use Next.js Proxy to rewrite, redirect, modify headers, or respond directly before a request completes.
related: related:
title: API Reference title: API Reference
description: Learn more about Proxy description: Learn more about Proxy
......
...@@ -222,11 +222,11 @@ Make the navigation from /settings to /dashboard instant using the next-cache-co ...@@ -222,11 +222,11 @@ Make the navigation from /settings to /dashboard instant using the next-cache-co
The [`next-partial-prefetching-adoption`](https://www.skills.sh/vercel/next.js/next-partial-prefetching-adoption) Skill moves an app onto [Partial Prefetching](/docs/app/guides/adopting-partial-prefetching), where links share one App Shell: The [`next-partial-prefetching-adoption`](https://www.skills.sh/vercel/next.js/next-partial-prefetching-adoption) Skill moves an app onto [Partial Prefetching](/docs/app/guides/adopting-partial-prefetching), where links share one App Shell:
1. Audits the existing `<Link prefetch={true}>` calls with you. 1. Audits existing `<Link prefetch={true}>` navigations and identifies the prefetched UI to preserve.
2. Turns the flag on and resolves the insights it surfaces. 2. Captures that UI in passing [`instant()`](/docs/app/guides/instant-navigation#prevent-regressions-with-e2e-tests) tests before enabling Partial Prefetching, then migrates each destination until the same tests pass unchanged.
3. Marks the routes whose URL data might be worth prefetching later. 3. Enables the flag, resolves the URL-data insights it surfaces, and marks optional per-link prefetching candidates for later.
It needs [Cache Components](/docs/app/getting-started/caching) already adopted. It needs [Cache Components](/docs/app/getting-started/caching) already adopted and a production-like build it can run for prefetch verification.
```bash filename="Terminal" ```bash filename="Terminal"
npx skills add vercel/next.js --skill next-partial-prefetching-adoption npx skills add vercel/next.js --skill next-partial-prefetching-adoption
......
...@@ -89,7 +89,7 @@ export const instant = false ...@@ -89,7 +89,7 @@ export const instant = false
You don't have to migrate every route at once. `instant = false` lets you get the whole app building and running first, then convert routes one at a time: You don't have to migrate every route at once. `instant = false` lets you get the whole app building and running first, then convert routes one at a time:
1. **Enable the flag and remove the route segment configs** (`dynamic`, `revalidate`, `fetchCache`). Routes that still render instantly need no further work. 1. **Enable the flag and migrate each route segment config.** Follow the relevant sections below for [`dynamic = "force-dynamic"`](#dynamic--force-dynamic), [`dynamic = "force-static"`](#dynamic--force-static), [`revalidate`](#revalidate), and [`fetchCache`](#fetchcache). For routes with dynamic params, also follow the [`generateStaticParams`](#generatestaticparams-and-dynamicparams) guidance. Routes that still render instantly need no further work.
2. **Opt out the routes that aren't ready.** Where an insight or error appears, set `instant = false` on the segment that raised it. To do this in one pass across the whole app, run the [`cache-components-instant-false`](/docs/app/guides/upgrading/codemods#cache-components-instant-false) codemod, which adds the opt-out to every `page`, `layout`, and `default` that doesn't already declare `instant`: 2. **Opt out the routes that aren't ready.** Where an insight or error appears, set `instant = false` on the segment that raised it. To do this in one pass across the whole app, run the [`cache-components-instant-false`](/docs/app/guides/upgrading/codemods#cache-components-instant-false) codemod, which adds the opt-out to every `page`, `layout`, and `default` that doesn't already declare `instant`:
```bash filename="Terminal" ```bash filename="Terminal"
...@@ -437,6 +437,14 @@ export async function getUser(id) { ...@@ -437,6 +437,14 @@ export async function getUser(id) {
Like the `fetch` Data Cache, `unstable_cache` persists cached values across deployments and serverless instances, while `use cache` does not. See [`fetch` cache options](#fetch-cache-options) above for the storage details. Like the `fetch` Data Cache, `unstable_cache` persists cached values across deployments and serverless instances, while `use cache` does not. See [`fetch` cache options](#fetch-cache-options) above for the storage details.
## `React.cache`
**Usually no change.** `React.cache` continues to deduplicate matching calls within a React render.
However, each Cache Function has an isolated React cache scope. Calls from separate Cache Functions do not share a `React.cache` result, such as when one Cache Function preloads data and another consumes it.
When a helper reads request data and matching calls need to share work across Cache Function scopes, replace the React wrapper with [`'use cache: private'`](/docs/app/api-reference/directives/use-cache-private). If the function only needs request-scoped deduplication, use `cacheLife({ stale: Infinity })` so it does not lower the route's stale time. Private Cache Function results are not stored in a server cache across production requests.
## On-demand revalidation (`revalidateTag`, `revalidatePath`, `updateTag`) ## On-demand revalidation (`revalidateTag`, `revalidatePath`, `updateTag`)
On-demand invalidation still works by tagging cached data and expiring it after an event. Tag data with [`cacheTag`](/docs/app/api-reference/functions/cacheTag) inside a `use cache` function instead of the `fetch` `next.tags` option, then choose the invalidation API by the behavior you want: On-demand invalidation still works by tagging cached data and expiring it after an event. Tag data with [`cacheTag`](/docs/app/api-reference/functions/cacheTag) inside a `use cache` function instead of the `fetch` `next.tags` option, then choose the invalidation API by the behavior you want:
...@@ -561,6 +569,8 @@ Cache Components changes how [dynamic routes](/docs/app/api-reference/file-conve ...@@ -561,6 +569,8 @@ Cache Components changes how [dynamic routes](/docs/app/api-reference/file-conve
**Returning an empty array now errors.** Without Cache Components, returning `[]` defers every path to the first runtime visit. With Cache Components, [`generateStaticParams`](/docs/app/api-reference/functions/generate-static-params) must return at least one param so Next.js can prerender the route and validate it produces a non-empty [static shell](/docs/app/glossary#static-shell). An empty array raises [`empty-generate-static-params`](/docs/messages/empty-generate-static-params). **Returning an empty array now errors.** Without Cache Components, returning `[]` defers every path to the first runtime visit. With Cache Components, [`generateStaticParams`](/docs/app/api-reference/functions/generate-static-params) must return at least one param so Next.js can prerender the route and validate it produces a non-empty [static shell](/docs/app/glossary#static-shell). An empty array raises [`empty-generate-static-params`](/docs/messages/empty-generate-static-params).
Keep `generateStaticParams` and return at least one real param. Removing the export opts the route out of ISR, so Next.js renders it on every request, even when it uses `use cache` for data. Read [ISR with Cache Components](/docs/app/guides/incremental-static-regeneration-cache-components) to learn how `generateStaticParams` prerenders dynamic routes and upgrades unlisted paths after their first visit.
```tsx filename="app/blog/[slug]/page.tsx" switcher ```tsx filename="app/blog/[slug]/page.tsx" switcher
// Before - defer all paths to runtime // Before - defer all paths to runtime
export async function generateStaticParams() { export async function generateStaticParams() {
......
...@@ -17,7 +17,13 @@ The HTML [`<video>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/v ...@@ -17,7 +17,13 @@ The HTML [`<video>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/v
```jsx filename="app/ui/video.jsx" ```jsx filename="app/ui/video.jsx"
export function Video() { export function Video() {
return ( return (
<video width="320" height="240" controls preload="none"> <video
width="320"
height="240"
poster="/path/to/poster.jpg"
controls
preload="none"
>
<source src="/path/to/video.mp4" type="video/mp4" /> <source src="/path/to/video.mp4" type="video/mp4" />
<track <track
src="/path/to/captions.vtt" src="/path/to/captions.vtt"
...@@ -42,6 +48,7 @@ export function Video() { ...@@ -42,6 +48,7 @@ export function Video() {
| `autoPlay` | Automatically starts playing the video when the page loads. Note: Autoplay policies vary across browsers. | `<video autoPlay />` | | `autoPlay` | Automatically starts playing the video when the page loads. Note: Autoplay policies vary across browsers. | `<video autoPlay />` |
| `loop` | Loops the video playback. | `<video loop />` | | `loop` | Loops the video playback. | `<video loop />` |
| `muted` | Mutes the audio by default. Often used with `autoPlay`. | `<video muted />` | | `muted` | Mutes the audio by default. Often used with `autoPlay`. | `<video muted />` |
| `poster` | An image shown in the video's box until the first frame is available. | `<video poster="/poster.jpg" />` |
| `preload` | Specifies how the video is preloaded. Values: `none`, `metadata`, `auto`. | `<video preload="none" />` | | `preload` | Specifies how the video is preloaded. Values: `none`, `metadata`, `auto`. | `<video preload="none" />` |
| `playsInline` | Enables inline playback on iOS devices, often necessary for autoplay to work on iOS Safari. | `<video playsInline />` | | `playsInline` | Enables inline playback on iOS devices, often necessary for autoplay to work on iOS Safari. | `<video playsInline />` |
...@@ -51,6 +58,8 @@ For a comprehensive list of video attributes, refer to the [MDN documentation](h ...@@ -51,6 +58,8 @@ For a comprehensive list of video attributes, refer to the [MDN documentation](h
### Video best practices ### Video best practices
- **Dimensions:** Set `width` and `height`, or a CSS `aspect-ratio`, so the browser reserves the box before the file loads. A video without dimensions collapses and then pushes the rest of the page down, which counts against [Cumulative Layout Shift](https://web.dev/articles/cls).
- **Poster Image:** Use `poster` to fill that reserved box while the video loads, especially with `preload="none"`, where no frame is fetched until playback starts.
- **Fallback Content:** When using the `<video>` tag, include fallback content inside the tag for browsers that do not support video playback. - **Fallback Content:** When using the `<video>` tag, include fallback content inside the tag for browsers that do not support video playback.
- **Subtitles or Captions:** Include subtitles or captions for users who are deaf or hard of hearing. Utilize the [`<track>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/track) tag with your `<video>` elements to specify caption file sources. - **Subtitles or Captions:** Include subtitles or captions for users who are deaf or hard of hearing. Utilize the [`<track>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/track) tag with your `<video>` elements to specify caption file sources.
- **Accessible Controls:** Standard HTML5 video controls are recommended for keyboard navigation and screen reader compatibility. For advanced needs, consider third-party players like [react-player](https://github.com/cookpete/react-player) or [video.js](https://videojs.com/), which offer accessible controls and consistent browser experience. - **Accessible Controls:** Standard HTML5 video controls are recommended for keyboard navigation and screen reader compatibility. For advanced needs, consider third-party players like [react-player](https://github.com/cookpete/react-player) or [video.js](https://videojs.com/), which offer accessible controls and consistent browser experience.
...@@ -77,8 +86,11 @@ export default function Page() { ...@@ -77,8 +86,11 @@ export default function Page() {
| `allowFullScreen` | Allows the iframe content to be displayed in full-screen mode. | `<iframe allowFullScreen />` | | `allowFullScreen` | Allows the iframe content to be displayed in full-screen mode. | `<iframe allowFullScreen />` |
| `sandbox` | Enables an extra set of restrictions on the content within the iframe. | `<iframe sandbox />` | | `sandbox` | Enables an extra set of restrictions on the content within the iframe. | `<iframe sandbox />` |
| `loading` | Optimize loading behavior (e.g., lazy loading). | `<iframe loading="lazy" />` | | `loading` | Optimize loading behavior (e.g., lazy loading). | `<iframe loading="lazy" />` |
| `style` | Apply CSS, such as an `aspect-ratio` to keep the box a fixed shape. | `<iframe style={{ border: 0 }} />` |
| `title` | Provides a title for the iframe to support accessibility. | `<iframe title="Description" />` | | `title` | Provides a title for the iframe to support accessibility. | `<iframe title="Description" />` |
An iframe without dimensions collapses until its content loads, the same as a video. Give it `width` and `height` or an `aspect-ratio`, particularly with `loading="lazy"`, where the embed can resolve long after the surrounding page has painted.
For a comprehensive list of iframe attributes, refer to the [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe#attributes). For a comprehensive list of iframe attributes, refer to the [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe#attributes).
### Choosing a video embedding method ### Choosing a video embedding method
......
...@@ -11,14 +11,16 @@ related: ...@@ -11,14 +11,16 @@ related:
- app/api-reference/functions/cacheTag - app/api-reference/functions/cacheTag
--- ---
The `'use cache: private'` directive allows functions to access runtime request APIs like `cookies()`, `headers()`, and `searchParams` within a cached scope. However, results are **never stored on the server**, they're cached only in the browser's memory and do not persist across page reloads. The `'use cache: private'` directive allows functions to access runtime request APIs like `cookies()`, `headers()`, and `searchParams` within a cached scope. In production, matching calls within one request can reuse the same result, but Next.js does not store it in a server cache across requests.
The client router can keep the rendered output in browser memory for the [`stale` time](/docs/app/api-reference/functions/cacheLife#client-cache-behavior) configured with `cacheLife`. This client-side cache does not persist across page reloads.
Reach for `'use cache: private'` when: Reach for `'use cache: private'` when:
- You want to cache a function that already accesses runtime data, and refactoring to [move the runtime access outside and pass values as arguments](/docs/app/getting-started/caching#working-with-runtime-apis) is not practical. - You want to cache a function that already accesses runtime data, and refactoring to [move the runtime access outside and pass values as arguments](/docs/app/getting-started/caching#working-with-runtime-apis) is not practical.
- Compliance requirements prevent storing certain data on the server, even temporarily - You need request-specific data to be excluded from server caches that persist across production requests.
Because this directive accesses runtime data, the function executes on every server render and is excluded from running during [static shell](/docs/app/getting-started/caching#prerendering) generation. Private Cache Functions run at request time and are excluded from [static shell](/docs/app/getting-started/caching#prerendering) generation. To start a private Cache Function before a component needs its result, see [Preloading data](/docs/app/getting-started/fetching-data#preloading-data).
It is **not** possible to configure custom cache handlers for `'use cache: private'`. It is **not** possible to configure custom cache handlers for `'use cache: private'`.
...@@ -149,7 +151,13 @@ async function getRecommendations(productId) { ...@@ -149,7 +151,13 @@ async function getRecommendations(productId) {
} }
``` ```
> **Good to know**: The `stale` time must be at least 30 seconds for per-link prefetching to work, and at least 5 minutes for the content to be included in the route's [App Shell](/docs/app/glossary#app-shell). See [`cacheLife` prerendering behavior](/docs/app/api-reference/functions/cacheLife#prerendering-behavior) for details. > **Good to know:** The `stale` time must be at least 30 seconds for per-link prefetching to work, and at least 5 minutes for the content to be included in the route's [App Shell](/docs/app/glossary#app-shell). See [`cacheLife` prerendering behavior](/docs/app/api-reference/functions/cacheLife#prerendering-behavior) for details.
### Configuring the client stale time
Private Cache Functions contribute their `stale` time to the route's [Client Cache](/docs/app/glossary#client-cache). If a function only needs request-scoped deduplication, use `cacheLife({ stale: Infinity })` to keep it from lowering the route's stale time.
Next.js uses the shortest stale time from the route's cache entries, so another cache or route setting can still set a finite value. Setting `stale` to `Infinity` does not store the private result on the server across production requests. Use a finite value when the client router should revalidate personalized output after a known interval.
## Request APIs allowed in private caches ## Request APIs allowed in private caches
......
...@@ -256,7 +256,7 @@ Proxy defaults to using the Node.js runtime. The [`runtime`](/docs/app/api-refer ...@@ -256,7 +256,7 @@ Proxy defaults to using the Node.js runtime. The [`runtime`](/docs/app/api-refer
## Advanced Proxy flags ## Advanced Proxy flags
In `v13.1` of Next.js two additional flags were introduced for proxy, `skipProxyUrlNormalize` (formerly `skipMiddlewareUrlNormalize`) and `skipTrailingSlashRedirect` to handle advanced use cases. In `v13.1` of Next.js two additional flags were introduced for proxy, [`skipProxyUrlNormalize`](/docs/app/api-reference/config/next-config-js/skipProxyUrlNormalize) (formerly `skipMiddlewareUrlNormalize`) and [`skipTrailingSlashRedirect`](/docs/app/api-reference/config/next-config-js/skipTrailingSlashRedirect) to handle advanced use cases.
`skipTrailingSlashRedirect` disables Next.js redirects for adding or removing trailing slashes. This allows custom handling inside proxy to maintain the trailing slash for some paths but not others, which can make incremental migrations easier. `skipTrailingSlashRedirect` disables Next.js redirects for adding or removing trailing slashes. This allows custom handling inside proxy to maintain the trailing slash for some paths but not others, which can make incremental migrations easier.
...@@ -477,7 +477,7 @@ When you use `NextResponse.rewrite()`, Next.js automatically propagates the requ ...@@ -477,7 +477,7 @@ When you use `NextResponse.rewrite()`, Next.js automatically propagates the requ
If you implement custom rewrite logic with `fetch()` instead of `NextResponse.rewrite()`, you can run into missing RSC headers unless you forward them manually. If you implement custom rewrite logic with `fetch()` instead of `NextResponse.rewrite()`, you can run into missing RSC headers unless you forward them manually.
For custom `fetch` rewrite setups, you can also enable `skipProxyUrlNormalize` in `next.config.js` so your rewrite logic can receive the necessary URL shape and RSC headers from the provided request object: For custom `fetch` rewrite setups, you can also enable [`skipProxyUrlNormalize`](/docs/app/api-reference/config/next-config-js/skipProxyUrlNormalize) in `next.config.js` so your rewrite logic can receive the necessary URL shape and RSC headers from the provided request object:
```js filename="next.config.js" ```js filename="next.config.js"
module.exports = { module.exports = {
......
...@@ -16,3 +16,25 @@ module.exports = { ...@@ -16,3 +16,25 @@ module.exports = {
allowedDevOrigins: ['local-origin.dev', '*.local-origin.dev'], allowedDevOrigins: ['local-origin.dev', '*.local-origin.dev'],
} }
``` ```
Only the [`hostname`](https://developer.mozilla.org/en-US/docs/Web/API/URL/hostname) of the request's `Origin` header is matched against your entries. For a request from `http://local-origin.dev:3000/dashboard?tab=1`, that is `local-origin.dev`. The scheme, the port, the path, and the query string are ignored. Write your entries that way too, without `https://` and without a port.
A no-cors cross-site request, such as a script tag loading a dev asset, sends no `Origin` header. Those are matched on the `Referer` hostname instead.
Entries can also expand, through two wildcards: a `*` stands in for exactly one label of the hostname, and `**` for one or more. That is why the example above lists two entries, one for the bare hostname and one for its subdomains.
| Entry | Matches | Does not match |
| --------------------- | --------------------------------------------------- | ---------------------------------------------- |
| `local-origin.dev` | `local-origin.dev` | `team.local-origin.dev` |
| `*.local-origin.dev` | `team.local-origin.dev` | `local-origin.dev`, `team.eu.local-origin.dev` |
| `**.local-origin.dev` | `team.local-origin.dev`, `team.eu.local-origin.dev` | `local-origin.dev` |
Partial replacement is not supported. Write `*.local-origin.dev`, rather than `team-*.local-origin.dev`. Using `**` is only supported at the start of the pattern.
The dev server already allows `localhost`, its subdomains, and the hostname it was started with. Any other hostname needs an entry, such as a tunnel used for remote development:
```js filename="next.config.js"
module.exports = {
allowedDevOrigins: ['*.tunnel.example.com'],
}
```
...@@ -10,7 +10,7 @@ Options for configuring Server Actions behavior in your Next.js application. For ...@@ -10,7 +10,7 @@ Options for configuring Server Actions behavior in your Next.js application. For
## `allowedOrigins` ## `allowedOrigins`
A list of extra safe origin domains from which Server Actions can be invoked. Next.js compares the origin of a Server Action request with the host domain, ensuring they match to prevent CSRF attacks. If not provided, only the same origin is allowed. A list of extra safe hosts from which Server Actions can be invoked. To prevent CSRF attacks, Next.js compares the host in a request's `Origin` header against the app's own host, taken from `x-forwarded-host` or `host`, and rejects the action when the two differ. If not provided, only the same origin is allowed. A request that carries no `Origin` header at all is allowed through with a warning rather than rejected.
```js filename="next.config.js" ```js filename="next.config.js"
/** @type {import('next').NextConfig} */ /** @type {import('next').NextConfig} */
...@@ -24,6 +24,38 @@ module.exports = { ...@@ -24,6 +24,38 @@ module.exports = {
} }
``` ```
Only the [`host`](https://developer.mozilla.org/en-US/docs/Web/API/URL/host) of the request's `Origin` header is matched against your entries, which is the hostname plus the port when the URL carries one. For a request from `https://my-proxy.com/checkout`, that is `my-proxy.com`. For one from `https://my-proxy.com:8443/checkout`, `my-proxy.com:8443`. Write your entries the same way.
Entries can also expand, through two wildcards: a `*` stands in for exactly one label of the host, and `**` for one or more. That is why the example above lists two entries, one for the bare host and one for its subdomains.
| Entry | Matches | Does not match |
| ------------------- | ----------------------------------------- | --------------------------------------- |
| `my-proxy.com` | `my-proxy.com` | `my-proxy.com:8443`, `app.my-proxy.com` |
| `*.my-proxy.com` | `app.my-proxy.com` | `my-proxy.com`, `app.my-proxy.com:8443` |
| `**.my-proxy.com` | `app.my-proxy.com`, `app.eu.my-proxy.com` | `my-proxy.com` |
| `my-proxy.com:8443` | `my-proxy.com:8443` | `my-proxy.com` |
Partial replacement is not supported. Write `*.my-proxy.com`, rather than `app-*.my-proxy.com`. Using `**` is only supported at the start of the pattern. A port cannot be wildcarded, so write it out in full: `my-proxy.com:8443`, or `*.my-proxy.com:8443` for its subdomains.
Behind a reverse proxy, no entry is needed as long as the proxy forwards the public host in `x-forwarded-host`. When it forwards its own host instead, the browser sends `my-proxy.com` while the server reports something like `localhost:3000`, and that mismatch is what this list is for: the host visible in the browser's address bar is the one to add, not the internal one the server reports.
The check runs in production as well as in development, so the list applies to your deployed app and not only to local work.
For example, remote development through a tunnel needs the tunnel hostname in two places: in [`allowedDevOrigins`](/docs/app/api-reference/config/next-config-js/allowedDevOrigins), so the dev server serves its own assets and endpoints, and here, so actions from it are accepted:
```js filename="next.config.js"
/** @type {import('next').NextConfig} */
module.exports = {
allowedDevOrigins: ['*.tunnel.example.com'],
experimental: {
serverActions: {
allowedOrigins: ['*.tunnel.example.com'],
},
},
}
```
## `bodySizeLimit` ## `bodySizeLimit`
By default, the maximum size of the request body sent to a Server Action is 1MB, to prevent the consumption of excessive server resources in parsing large amounts of data, as well as potential DDoS attacks. By default, the maximum size of the request body sent to a Server Action is 1MB, to prevent the consumption of excessive server resources in parsing large amounts of data, as well as potential DDoS attacks.
......
---
title: skipProxyUrlNormalize
description: Let Proxy see the original request instead of Next.js's normalized version. Formerly skipMiddlewareUrlNormalize.
---
{/* The content of this doc is shared between the app and pages router. You can use the `<PagesOnly>Content</PagesOnly>` component to add content that is specific to the Pages Router. Any shared content should not be wrapped in a component. */}
Enabling `skipProxyUrlNormalize` lets [Proxy](/docs/app/api-reference/file-conventions/proxy) see the original request instead of Next.js's normalized version. This includes internal URLs, query parameters, and headers used during client-side navigation.
**Most projects don't need this option.** It is one of the [advanced Proxy flags](/docs/app/api-reference/file-conventions/proxy#advanced-proxy-flags), meant for specific routing cases and debugging.
```ts filename="next.config.ts" switcher
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
skipProxyUrlNormalize: true,
}
export default nextConfig
```
```js filename="next.config.js" switcher
/** @type {import('next').NextConfig} */
const nextConfig = {
skipProxyUrlNormalize: true,
}
module.exports = nextConfig
```
## Reference
During client-side navigation, Next.js uses an internal request rather than requesting the destination URL as a full document load. By default, Next.js normalizes that request before it reaches Proxy, so Proxy sees the same destination URL for both client-side navigation and a full page load.
Next.js also normalizes what Proxy returns, so any URL you rewrite or redirect to is rewritten to match.
With `skipProxyUrlNormalize: true`, neither normalization runs. Proxy receives the request as sent, and the destinations it rewrites or redirects to are sent as written:
| Default | With `skipProxyUrlNormalize: true` |
| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------- |
| `request.nextUrl` resolves the internal data URL back to the route path and extracts the locale | Holds the requested pathname as sent |
| `request.url` is the normalized URL | Is the original request URL |
| The internal `_rsc` query parameter is stripped | Preserved |
| Next.js internal navigation headers (`rsc`, `next-router-state-tree`, `next-router-prefetch`, `next-router-segment-prefetch`, `next-hmr-refresh`) are removed from `request.headers` | Preserved |
| `NextResponse.rewrite()` destinations are re-serialized with the build ID | Sent as written |
| `NextResponse.redirect()` `Location` is rewritten to a relative URL | Sent as written, trailing slash preserved |
| With [`trailingSlash: true`](/docs/app/api-reference/config/next-config-js/trailingSlash), a trailing slash is appended before Proxy runs | Pathname passed through unchanged |
### Deprecated alias
The former name of this option is `skipMiddlewareUrlNormalize`, from when Proxy was called Middleware. It still works and logs a deprecation warning. Setting both at once throws:
```bash filename="Terminal"
Config options `skipProxyUrlNormalize` and `skipMiddlewareUrlNormalize` cannot be set at the same time. Please use `skipProxyUrlNormalize` instead.
```
The [version 16 codemod](/docs/app/guides/upgrading/codemods#160) renames it for you.
## Good to know
- Avoid using the internal navigation headers to return different content for client-side navigation and full page loads.
- You do not need this option to limit which routes Proxy runs on. The [`matcher`](/docs/app/api-reference/file-conventions/proxy#matcher) config still matches the destination URL either way.
- Only the request and response Proxy sees change. Filesystem routing, `redirects`, and `rewrites` from `next.config.js` behave the same.
## Examples
### Reading the URL as the client sent it
<AppOnly>
During client-side navigation, Next.js adds an `_rsc` query parameter and its internal navigation headers to the request. With the option enabled, Proxy can read both.
```ts filename="proxy.ts" switcher
import type { NextRequest } from 'next/server'
export default function proxy(request: NextRequest) {
console.log(request.nextUrl.searchParams.get('_rsc'))
// Enabled: the value Next.js added to the request
// Disabled: null
console.log(request.headers.get('rsc'))
// Enabled: '1' during client-side navigation
// Disabled: null
}
```
```js filename="proxy.js" switcher
export default function proxy(request) {
console.log(request.nextUrl.searchParams.get('_rsc'))
// Enabled: the value Next.js added to the request
// Disabled: null
console.log(request.headers.get('rsc'))
// Enabled: '1' during client-side navigation
// Disabled: null
}
```
</AppOnly>
<PagesOnly>
During client-side navigation, Next.js requests a `/_next/data` URL instead of the destination URL. With the option enabled, Proxy sees that URL as sent.
```ts filename="proxy.ts" switcher
import type { NextRequest } from 'next/server'
export default function proxy(request: NextRequest) {
const { pathname } = request.nextUrl
// Request: GET /_next/data/build-id/hello.json
console.log(pathname)
// Enabled: /_next/data/build-id/hello.json
// Disabled: /hello
}
```
```js filename="proxy.js" switcher
export default function proxy(request) {
const { pathname } = request.nextUrl
// Request: GET /_next/data/build-id/hello.json
console.log(pathname)
// Enabled: /_next/data/build-id/hello.json
// Disabled: /hello
}
```
</PagesOnly>
## Version History
| Version | Changes |
| --------- | --------------------------------------------------------------------- |
| `v16.0.0` | Renamed from `skipMiddlewareUrlNormalize` to `skipProxyUrlNormalize`. |
| `v13.1.0` | `skipMiddlewareUrlNormalize` added. |
---
title: skipTrailingSlashRedirect
description: Disable the automatic trailing slash redirects so you can handle trailing slashes yourself in Proxy.
---
{/* The content of this doc is shared between the app and pages router. You can use the `<PagesOnly>Content</PagesOnly>` component to add content that is specific to the Pages Router. Any shared content should not be wrapped in a component. */}
Enabling `skipTrailingSlashRedirect` turns off the automatic redirects that add or remove a trailing slash. You handle any redirecting you still want in [Proxy](/docs/app/api-reference/file-conventions/proxy).
**Most projects don't need this option.** It is one of the [advanced Proxy flags](/docs/app/api-reference/file-conventions/proxy#advanced-proxy-flags), meant for specific routing cases and debugging.
```ts filename="next.config.ts" switcher
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
skipTrailingSlashRedirect: true,
}
export default nextConfig
```
```js filename="next.config.js" switcher
/** @type {import('next').NextConfig} */
const nextConfig = {
skipTrailingSlashRedirect: true,
}
module.exports = nextConfig
```
## Reference
By default, Next.js redirects every request so the trailing slash matches your [`trailingSlash`](/docs/app/api-reference/config/next-config-js/trailingSlash) setting.
| `trailingSlash` | Request | Default response |
| --------------- | --------- | --------------------------- |
| `false` | `/about` | `200` |
| `false` | `/about/` | `308` redirect to `/about` |
| `true` | `/about` | `308` redirect to `/about/` |
| `true` | `/about/` | `200` |
Enabling `skipTrailingSlashRedirect` affects both server responses and client-side navigation:
- Both `/about` and `/about/` return `200`. Neither redirects to the other.
- Next.js stops changing trailing slashes during client-side navigation. [`<Link>`](/docs/app/api-reference/components/link) and router URLs keep the path exactly as written.
Your own `redirects` and `rewrites` from `next.config.js` still apply.
### Paths that contain a dot
If the last path segment contains a dot, Next.js treats the path as a file and removes the trailing slash, regardless of the `trailingSlash` setting. A dot in an earlier segment has no effect, except under `.well-known/`, which is exempt from the default redirects when `trailingSlash` is `true`.
| Request | `trailingSlash: true` | `trailingSlash: false` | `skipTrailingSlashRedirect: true` |
| ------------------------- | ---------------------------------- | ------------------------------------------ | --------------------------------- |
| `/about` | `308` redirect to `/about/` | `200` | `200` |
| `/about/` | `200` | `308` redirect to `/about` | `200` |
| `/gcc.git/` | `308` redirect to `/gcc.git` | `308` redirect to `/gcc.git` | `200` |
| `/version/1.2.3/` | `308` redirect to `/version/1.2.3` | `308` redirect to `/version/1.2.3` | `200` |
| `/version/1.2.3/my-page/` | `200` | `308` redirect to `/version/1.2.3/my-page` | `200` |
| `/.well-known/x/` | `200` | `308` redirect to `/.well-known/x` | `200` |
With `skipTrailingSlashRedirect` enabled, none of these redirects are generated and every path is served at whichever form was requested.
## Good to know
- Keep setting [`trailingSlash`](/docs/app/api-reference/config/next-config-js/trailingSlash) as you did before. It still controls the URLs Next.js generates and the output filenames for [`output: 'export'`](/docs/app/guides/static-exports).
- With `output: 'export'`, this preserves the `href` instead of resolving `/me` to `/me/`. See [Static Exports](/docs/app/guides/static-exports).
- Serving one page at both `/about` and `/about/` gives search engines two URLs for it. Set a [canonical URL](/docs/app/api-reference/functions/generate-metadata#alternates) in your metadata, or redirect in [Proxy](/docs/app/api-reference/file-conventions/proxy).
## Examples
### Handling trailing slashes in Proxy
With `skipTrailingSlashRedirect` enabled, Next.js no longer adds trailing slashes, but Proxy can still add them selectively. This example adds a trailing slash to your own routes while leaving a set of legacy prefixes untouched, which makes an incremental migration easier.
```ts filename="proxy.ts" switcher
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
const legacyPrefixes = ['/docs', '/blog']
export default function proxy(request: NextRequest) {
const { pathname } = request.nextUrl
if (legacyPrefixes.some((prefix) => pathname.startsWith(prefix))) {
return NextResponse.next()
}
// Apply trailing slash handling, skipping files and `.well-known` paths
if (
!pathname.endsWith('/') &&
!pathname.match(/((?!\.well-known(?:\/.*)?)(?:[^/]+\/)*[^/]+\.\w+)/)
) {
return NextResponse.redirect(new URL(`${pathname}/`, request.nextUrl))
}
}
```
```js filename="proxy.js" switcher
import { NextResponse } from 'next/server'
const legacyPrefixes = ['/docs', '/blog']
export default function proxy(request) {
const { pathname } = request.nextUrl
if (legacyPrefixes.some((prefix) => pathname.startsWith(prefix))) {
return NextResponse.next()
}
// Apply trailing slash handling, skipping files and `.well-known` paths
if (
!pathname.endsWith('/') &&
!pathname.match(/((?!\.well-known(?:\/.*)?)(?:[^/]+\/)*[^/]+\.\w+)/)
) {
return NextResponse.redirect(new URL(`${pathname}/`, request.nextUrl))
}
}
```
## Version History
| Version | Changes |
| --------- | ---------------------------------- |
| `v13.1.0` | `skipTrailingSlashRedirect` added. |
...@@ -11,7 +11,7 @@ The `taint` option enables support for experimental React APIs for tainting obje ...@@ -11,7 +11,7 @@ The `taint` option enables support for experimental React APIs for tainting obje
- [`experimental_taintObjectReference`](https://react.dev/reference/react/experimental_taintObjectReference) taint objects references. - [`experimental_taintObjectReference`](https://react.dev/reference/react/experimental_taintObjectReference) taint objects references.
- [`experimental_taintUniqueValue`](https://react.dev/reference/react/experimental_taintUniqueValue) to taint unique values. - [`experimental_taintUniqueValue`](https://react.dev/reference/react/experimental_taintUniqueValue) to taint unique values.
> **Good to know**: Activating this flag also enables the React `experimental` channel for `app` directory. > **Good to know**: Activating this flag also enables the React `experimental` channel for `app` directory, and taints `process.env` so it cannot be passed whole to a Client Component.
```ts filename="next.config.ts" switcher ```ts filename="next.config.ts" switcher
import type { NextConfig } from 'next' import type { NextConfig } from 'next'
...@@ -51,6 +51,7 @@ It is recommended to model your data and APIs so that sensitive data is not retu ...@@ -51,6 +51,7 @@ It is recommended to model your data and APIs so that sensitive data is not retu
## Caveats ## Caveats
- Tainting can only keep track of objects by reference. Copying an object creates an untainted version, which loses all guarantees given by the API. You'll need to taint the copy. - Tainting can only keep track of objects by reference. Copying an object creates an untainted version, which loses all guarantees given by the API. You'll need to taint the copy.
- The built-in `process.env` taint applies to the object reference only. Reading individual variables such as `process.env.MY_VAR` and passing the resulting string to a Client Component is unaffected, as is passing a copy like `{ ...process.env }`.
- Tainting cannot keep track of data derived from a tainted value. You also need to taint the derived value. - Tainting cannot keep track of data derived from a tainted value. You also need to taint the derived value.
- Values are tainted for as long as their lifetime reference is within scope. See the [`experimental_taintUniqueValue` parameters reference](https://react.dev/reference/react/experimental_taintUniqueValue#parameters), for more information. - Values are tainted for as long as their lifetime reference is within scope. See the [`experimental_taintUniqueValue` parameters reference](https://react.dev/reference/react/experimental_taintUniqueValue#parameters), for more information.
......
--- ---
title: useReportWebVitals title: useReportWebVitals
description: useReportWebVitals description: Use the Next.js `useReportWebVitals` hook to send Core Web Vitals and custom performance metrics to analytics.
source: app/api-reference/functions/use-report-web-vitals source: app/api-reference/functions/use-report-web-vitals
--- ---
......
---
title: skipProxyUrlNormalize
description: Let Proxy see the original request instead of Next.js's normalized version. Formerly skipMiddlewareUrlNormalize.
source: app/api-reference/config/next-config-js/skipProxyUrlNormalize
---
{/* DO NOT EDIT. The content of this doc is generated from the source above. To edit the content of this page, navigate to the source page in your editor. You can use the `<PagesOnly>Content</PagesOnly>` component to add content that is specific to the Pages Router. Any shared content should not be wrapped in a component. */}
---
title: skipTrailingSlashRedirect
description: Disable the automatic trailing slash redirects so you can handle trailing slashes yourself in Proxy.
source: app/api-reference/config/next-config-js/skipTrailingSlashRedirect
---
{/* DO NOT EDIT. The content of this doc is generated from the source above. To edit the content of this page, navigate to the source page in your editor. You can use the `<PagesOnly>Content</PagesOnly>` component to add content that is specific to the Pages Router. Any shared content should not be wrapped in a component. */}
--- ---
title: turbopack title: turbopack
description: Configure Next.js with Turbopack-specific options description: Configure Next.js with Turbopack-specific options
version: experimental
source: app/api-reference/config/next-config-js/turbopack source: app/api-reference/config/next-config-js/turbopack
--- ---
......
...@@ -39,7 +39,10 @@ build/run obstacles, accumulated as you first hit them). ...@@ -39,7 +39,10 @@ build/run obstacles, accumulated as you first hit them).
and never for real production? Spellings: an explicit and never for real production? Spellings: an explicit
`EXPOSE_TESTING_API=1` for local production builds; `process.env.DEPLOY_ENV `EXPOSE_TESTING_API=1` for local production builds; `process.env.DEPLOY_ENV
=== 'staging'` for a generic CI/staging env var; `process.env.VERCEL_ENV === === 'staging'` for a generic CI/staging env var; `process.env.VERCEL_ENV ===
'preview'` on Vercel. 'preview'` on Vercel. Set the condition during `next build`, not only
`next start`. Otherwise `instant()` may not acquire the testing cookie
before the test times out; rebuild the artifact before debugging the
assertion.
3. **RUN**: how is the Playwright suite invoked, and against which 3. **RUN**: how is the Playwright suite invoked, and against which
`BASE_URL`? `BASE_URL`?
4. **TEST USER**: which account does the suite run as, and how does login 4. **TEST USER**: which account does the suite run as, and how does login
...@@ -64,7 +67,10 @@ build/run obstacles, accumulated as you first hit them). ...@@ -64,7 +67,10 @@ build/run obstacles, accumulated as you first hit them).
chosen mechanism. For a local `build && start` rig the artifact is the one chosen mechanism. For a local `build && start` rig the artifact is the one
freshly built, so no SHA probe is needed. Record the port, stop the previous freshly built, so no SHA probe is needed. Record the port, stop the previous
server before starting, fail the loop on `EADDRINUSE`, and verify the newly server before starting, fail the loop on `EADDRINUSE`, and verify the newly
started process owns the port before running the test. started process owns the port before running the test. `next start` can fork
a `next-server` child, so the launcher process ID may not own the port. Start
the server in a process group that the rig can stop as a unit, or discover
and stop the process listening on the recorded port before the next build.
## The file: copy, fill, commit as `instant-nav.rig.md` ## The file: copy, fill, commit as `instant-nav.rig.md`
......
# Production `instant()` rig
The preservation suite needs a production build that exposes the Next.js
testing API, a stable URL for that build, and a Playwright command that can
drive the audited Links. Discover this setup once, record it in
`instant-nav.rig.md`, and reuse it throughout adoption.
Read an existing `instant-nav.rig.md` before creating one. Inspect the
repository before asking the user:
- `package.json` scripts for build, start, and end-to-end tests
- `playwright.config.*` for `baseURL`, `webServer`, projects, and authentication
- `next.config.*` for existing `experimental` options
- CI, preview deployment, container, and hosting configuration
- test helpers for login, `storageState`, fixtures, flags, and seeded data
Ask only for details the repository cannot answer, such as unavailable
credentials or which remote environment may expose the testing API.
## What the rig must define
### Production build and server
Use `next build` followed by `next start`, or a remote artifact produced by the
same production build. Automatic prefetching does not run in `next dev`, so a
development server cannot verify preservation.
Record separate build and start commands. For a local rig, record the port,
stop any previous server before starting, fail on `EADDRINUSE`, and confirm the
new process owns the port before running Playwright. `next start` can fork a
`next-server` child, so the launcher process ID may not own the port. Start the
server in a process group that the rig can stop as a unit, or discover and stop
the process listening on the recorded port before the next build.
### Testing API
An `instant()` test against a production build requires
`experimental.exposeTestingApiInProductionBuild`. Gate it so real production
builds do not expose the API:
```ts filename="next.config.ts" highlight={3,8-10}
import type { NextConfig } from 'next'
const exposeTestingApi = process.env.EXPOSE_TESTING_API === '1'
const nextConfig: NextConfig = {
cacheComponents: true,
experimental: {
exposeTestingApiInProductionBuild: exposeTestingApi,
},
}
export default nextConfig
```
Merge the option into an existing `experimental` object instead of replacing
the project's other experimental options.
Set the condition while running `next build`. Setting it only for `next start`
is too late because the testing API is compiled into the production artifact.
When the artifact was built without it, Next.js does not activate the
navigation lock, so the test cannot distinguish prefetched UI from streamed
dynamic content. Rebuild with the condition enabled before interpreting the
results. Use the project's existing environment naming when it already
distinguishes test, staging, preview, and production builds.
### Test command and base URL
Record the exact Playwright command and how it receives the measured build's
URL. Reuse the project's package manager, Playwright configuration, projects,
and reporters. The suite must import `instant()` from `@next/playwright`. If
the dependencies are absent, install `@next/playwright` on the same release
line as the project's `next`, alongside `@playwright/test`.
For a local rig, a typical sequence is:
```bash filename="Terminal"
EXPOSE_TESTING_API=1 pnpm build
pnpm start --port 3000
BASE_URL=http://localhost:3000 pnpm playwright test tests/prefetch-preservation.spec.ts
```
Adapt the script names and port to the project. Keep the production server
running while the test command executes. Follow the public
[client-navigation test](https://nextjs.org/docs/app/guides/instant-navigation#prevent-regressions-with-e2e-tests): load the source route, confirm the real
Link is visible, then enter `instant()`, click, wait for the destination URL,
and assert the prefetched UI.
### Test context
Record the state required to reach the audited Links and destination UI:
- Use `public; no authentication` when the navigation is public.
- Otherwise record the test account and login mechanism, including a fixture,
`storageState`, API login, or seeded session.
- Record flags, plan, role, locale, seeded data, and other state that can change
which UI the test sees.
A test user is not required. The field exists to make authenticated and
state-dependent tests reproducible when the app needs one.
### Drift
List differences between the state used to choose the preservation target and
the state used by Playwright. Feature flags, permissions, empty test data, and
locale differences can make an assertion fail because the target is
unreachable, not because Partial Prefetching removed it. Write `none known`
only after checking the test context.
### Iteration loop
Record the complete loop the agent can repeat without rediscovering commands:
- Local: build with the testing API, start the new artifact, run the focused
suite, stop the server, edit, and repeat.
- Remote: push, wait for the measured artifact, verify it matches `HEAD`, run
the focused suite against its URL, edit, and repeat.
Note any step the agent cannot perform without the user, including deployment
approval, protected branches, secrets, or multi-factor authentication.
### Artifact liveness
For a remote rig, record how the test proves the deployment matches `HEAD`.
Prefer an endpoint or response header that exposes the deployed commit SHA. If
the app has neither, use the deployment provider's API to select the artifact
whose commit SHA matches `HEAD`.
A freshly completed local `build` followed by `start` does not need a SHA
probe. Record `n/a; local build and start`.
### Walls
Record build and run obstacles with their working resolution, such as required
environment variables, server-only imports that fail during prerendering,
unavailable credentials, or a process that keeps reclaiming the test port.
Reuse these notes on the next iteration.
## Write `instant-nav.rig.md`
Place this file at the repository root or next to the end-to-end configuration:
```md
# instant-nav rig: <project>
- BUILD: <commands or platform that builds and serves the measured production artifact>
- EXPOSE: <condition that enables exposeTestingApiInProductionBuild during build>
- RUN: <focused Playwright command and how it receives BASE_URL>
- TEST USER: <public/no auth, or account and login>; state: <flags, role, data, locale>
- DRIFT: <differences that could change the asserted UI>
- LOOP: <local build → start → test, or push → deploy → test>; agent limits: <...>
- LIVENESS: <deployed SHA check, or n/a for a local build and start>
- WALLS: <project-specific obstacles and their resolutions>
```
Every field needs a concrete value. `n/a` is valid only with a reason, such as
`TEST USER: public; no authentication` or `LIVENESS: n/a; local build and
start`.
## Check the rig before writing the baseline
Before recording the legacy prefetched UI:
1. Build with the testing API condition enabled.
2. Start or locate that exact artifact and confirm the base URL responds.
3. Run one focused `instant()` smoke test through a real `<Link>` navigation.
4. Confirm the test can reach its source Link and eventual destination UI in
the recorded test context.
Fix the rig before interpreting a preservation failure. A missing testing API,
stale deployment, unreachable target, or wrong test state is an environment
failure rather than evidence that the migration changed the prefetch.
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