Unverified Commit 7c16cc9f authored by Aurora Scharff's avatar Aurora Scharff Committed by GitHub

docs: add guide for optimizing the static shell (#97737)

## What?

Adds an **Optimizing the static shell** guide that follows one team
settings route through focused Suspense boundaries, deferred
authentication, cache-versus-stream decisions, loading-state reuse,
shared layouts, and parallel routes.

Updates `next-cache-components-optimizer` to use that guide and the
canonical Insight pages as its framework source of truth. The original
phase-based Skill workflow is preserved, including the production rig,
exact test contract, trustworthy RED-to-GREEN loop, parity check,
differential, and reporting. Reusable implementation guidance now links
to the corresponding guide section instead of being duplicated in
Skill-only references.

Clarifies that the optimizer can target either a direct page load or a
named client navigation. Both use the same App Shell patterns and
`instant()` verification loop. When the destination App Shell is already
instant and the goal is to include additional URL-specific content
before a click, the Skill hands off to the Partial Prefetching
optimizer.

Aligns the Cache Components and Partial Prefetching optimizers around
the same workflow: define the contract, reuse the production rig, prove
current behavior, make the smallest optimization, verify and ship. Their
framework-specific decisions remain separate. The Partial Prefetching
adoption rig also receives the shared visible, committed DOM-marker rule
because it uses the same `instant()` testing API.

## Why?

The optimizer's framework patterns are useful outside the agent
workflow. Keeping them in public docs gives developers and agents one
source of truth while each Skill stays focused on its product decision
and reliable production verification.

## Eval

The corrected-contract comparison uses Claude Opus 4.8 and Claude Sonnet
4.5 with a fixed Claude Haiku 4.5 judge. It compares the baseline,
bundled guide, production Skill from `canary`, and proposed local Skill.
The bundled-guide and Skill treatments use a local Next.js tarball
containing the new guide.

The eval now contains 11 granular checks so product behavior, test
quality, and workflow discipline are visible independently. They cover
configuration, direct and client-navigation `instant()` coverage, exact
shell markers, preserved data sources, reusable and request-time UI
placement, all completed-route variants, viewer-cookie behavior,
trustworthy RED, full-suite GREEN, and the bounded differential. The
prompt names the Aurora, Nebula, unknown-release, and viewer-cookie
parity cases explicitly.

All eight treatments were rerun against this 11-check rubric.

| Model | Treatment | Checks passed | Overall | Duration | Tokens
processed | Total run cost | Cost change |
| --- | --- | ---: | ---: | ---: | ---: | ---: | ---: |
| Opus 4.8 | Baseline | 9/11 | Fail | 26m 38s | 4.83M | $4.66 | — |
| Opus 4.8 | Bundled guide | 8/11 | Fail | 36m 36s | 4.99M | $5.29 |
+13.5% |
| Opus 4.8 | Production Skill | 9/11 | Fail | 28m 20s | 3.25M | $3.35 |
-28.0% |
| Opus 4.8 | Proposed Skill | **11/11** | **Pass** | 32m 9s | 5.25M |
$5.24 | +12.5% |
| Sonnet 4.5 | Baseline | 8/11 | Fail | 22m 31s | 2.73M | $1.29 | — |
| Sonnet 4.5 | Bundled guide | 8/11 | Fail | 17m 58s | 2.38M | $1.18 |
-8.1% |
| Sonnet 4.5 | Production Skill | 4/11 | Fail | 27m 18s | 2.94M | $1.38
| +7.3% |
| Sonnet 4.5 | Proposed Skill | 4/11 | Fail | 25m 26s | 5.49M | $2.53 |
+96.1% |

Token totals count each unique model message once and include uncached
input, cache creation, cache reads, and output. Total run cost applies
the current AI Gateway base rates to each token category. Judge cost is
excluded.

The eight runs processed 31.87M tokens and cost $24.91 in total,
excluding the judge. This is one run per model and treatment, so the
comparison is descriptive rather than a stable pass-rate measurement.

The proposed Opus Skill is the only treatment to pass every check.
Baseline and production Skill each passed 9/11, but both skipped the
bounded differential. Baseline also missed the viewer-cookie timing
lock. Production Skill omitted exact loading-state coverage. The
guide-only treatment implemented the product behavior but missed an
exact selector, trustworthy RED, and the differential.

The proposed Sonnet Skill preserved the exact `instant()` contract, but
replaced the existing runtime file read with a build-time import. It
then stopped using the documented production command, encountered port
conflicts from starting another Playwright server lifecycle, and never
completed parity, GREEN, or a valid differential. This is a model
adherence failure rather than a sandbox or credential failure. It shows
that the restored workflow is sufficient for Opus but still too easy for
Sonnet to abandon after it encounters test friction.

## Verification

- Local Next.js build passed.
- Prettier, TypeScript, ESLint through the commit hook, Alex, and diff
checks passed.
- Documentation link validation passed in CI.
- All eight treatments finalized against the current 11-check rubric.
parent 22f8122a
...@@ -531,6 +531,8 @@ Now `<Sidebar />`, `{children}`, and the Suspense fallback are all part of the s ...@@ -531,6 +531,8 @@ Now `<Sidebar />`, `{children}`, and the Suspense fallback are all part of the s
The same principle applies to `cookies()`, `headers()`, `searchParams`, and data fetches. See [Reusing data with `React.cache`](/docs/app/getting-started/fetching-data#reusing-data-with-reactcache) for a related pattern. The same principle applies to `cookies()`, `headers()`, `searchParams`, and data fetches. See [Reusing data with `React.cache`](/docs/app/getting-started/fetching-data#reusing-data-with-reactcache) for a related pattern.
For a complete workflow, see [Optimizing the static shell](/docs/app/guides/optimizing-the-static-shell).
### Instant navigation ### Instant navigation
Cache Components shipped in 16.0.0 with verification that direct visits to a route produce a static shell. Client navigations are different: a `<Suspense>` boundary that covers a direct visit may not be part of the render during a transition. Getting that structure right is easier when the framework steps in. Cache Components now validates these navigations too, giving you insights and errors that guide you to make navigations to your route instant. For example, wrap data in `<Suspense>`, cache it with `use cache`, or move where the access happens. Cache Components shipped in 16.0.0 with verification that direct visits to a route produce a static shell. Client navigations are different: a `<Suspense>` boundary that covers a direct visit may not be part of the render during a transition. Getting that structure right is easier when the framework steps in. Cache Components now validates these navigations too, giving you insights and errors that guide you to make navigations to your route instant. For example, wrap data in `<Suspense>`, cache it with `use cache`, or move where the access happens.
......
...@@ -24,7 +24,7 @@ Along the way, Next.js surfaces [instant navigation](/docs/app/guides/instant-na ...@@ -24,7 +24,7 @@ Along the way, Next.js surfaces [instant navigation](/docs/app/guides/instant-na
## Use the adoption skill (recommended) ## Use the adoption skill (recommended)
The [`next-partial-prefetching-adoption`](https://github.com/vercel/next.js/tree/canary/skills/next-partial-prefetching-adoption) skill drives this adoption with a coding agent. It reviews your `<Link prefetch={true}>` calls, captures the prefetched UI to preserve with [`instant()` tests](#verify-prefetched-ui-with-tests) when a production test rig is available, then enables the flag and checks each route for the insights this guide covers. The [`next-partial-prefetching-adoption`](/docs/app/guides/ai-agents#next-partial-prefetching-adoption) skill drives this adoption with a coding agent. It reviews your `<Link prefetch={true}>` calls, captures the prefetched UI to preserve with [`instant()` tests](#verify-prefetched-ui-with-tests) when a production test rig is available, then enables the flag and checks each route for the insights this guide covers.
Install the skill: Install the skill:
......
...@@ -221,13 +221,13 @@ Adopt Cache Components in this project using the next-cache-components-adoption ...@@ -221,13 +221,13 @@ Adopt Cache Components in this project using the next-cache-components-adoption
### `next-cache-components-optimizer` ### `next-cache-components-optimizer`
The [`next-cache-components-optimizer`](https://www.skills.sh/vercel/next.js/next-cache-components-optimizer) Skill takes a target route or set of routes and works toward the UI you want on screen at click time: The [`next-cache-components-optimizer`](https://www.skills.sh/vercel/next.js/next-cache-components-optimizer) Skill expands a target route's static shell to include the useful UI you want available on an initial load:
1. Writes a failing [`instant()`](/docs/app/guides/instant-navigation#prevent-regressions-with-e2e-tests) test for the UI you named. 1. Writes a failing [`instant()`](/docs/app/guides/instant-navigation#prevent-regressions-with-e2e-tests) test for the static-shell UI you named.
2. Refactors the route until it passes, often by moving a data read below a `<Suspense>` boundary. 2. Refactors the route until it passes, often by moving a data read below a `<Suspense>` boundary.
3. Commits the passing test with the refactoring, so it catches future regressions. 3. Commits the passing test with the refactoring, so it catches future regressions.
It needs a route that already builds with [Cache Components](/docs/app/getting-started/caching). Use it after adopting [Cache Components](/docs/app/getting-started/caching) to optimize an initial load or client navigation. To prefetch URL-specific content for an already-instant destination, use the [`next-partial-prefetching-optimizer`](#next-partial-prefetching-optimizer) instead.
```bash filename="Terminal" ```bash filename="Terminal"
npx skills add vercel/next.js --skill next-cache-components-optimizer npx skills add vercel/next.js --skill next-cache-components-optimizer
...@@ -236,7 +236,7 @@ npx skills add vercel/next.js --skill next-cache-components-optimizer ...@@ -236,7 +236,7 @@ npx skills add vercel/next.js --skill next-cache-components-optimizer
Then give the agent a prompt like: Then give the agent a prompt like:
```prompt ```prompt
Make the navigation from /settings to /dashboard instant using the next-cache-components-optimizer Skill. The header and the project list should be part of the instant UI. Optimize the static shell for /dashboard using the next-cache-components-optimizer Skill. On an initial load, the header and project list should be available immediately.
``` ```
### `next-partial-prefetching-adoption` ### `next-partial-prefetching-adoption`
......
...@@ -145,7 +145,7 @@ The **Navigation Inspector** in the Next.js DevTools freezes the page at its ini ...@@ -145,7 +145,7 @@ The **Navigation Inspector** in the Next.js DevTools freezes the page at its ini
Pair it with the React DevTools Suspense panel to see exactly which boundary covers which part of the page. See [Visualize loading states with the Next.js DevTools](#visualize-loading-states-with-the-nextjs-devtools) for the workflow. Pair it with the React DevTools Suspense panel to see exactly which boundary covers which part of the page. See [Visualize loading states with the Next.js DevTools](#visualize-loading-states-with-the-nextjs-devtools) for the workflow.
See [Maximizing the static shell](/docs/app/getting-started/caching#maximizing-the-static-shell) for patterns to reduce fallback coverage and pull more content into the shell. See [Optimizing the static shell](/docs/app/guides/optimizing-the-static-shell) for patterns to reduce fallback coverage and make more completed UI available immediately.
## A page that navigates instantly ## A page that navigates instantly
...@@ -373,19 +373,25 @@ Inside the callback, an initial page load shows the static UI and a client navig ...@@ -373,19 +373,25 @@ Inside the callback, an initial page load shows the static UI and a client navig
For client navigations, wait for the destination URL before asserting on its UI. Otherwise, a shared selector can match the source page before the destination commits. If the prefetched destination cannot commit, the URL wait times out and the test fails. For client navigations, wait for the destination URL before asserting on its UI. Otherwise, a shared selector can match the source page before the destination commits. If the prefetched destination cannot commit, the URL wait times out and the test fails.
Run these against `next dev`, where the testing API is enabled automatically. To run them in CI against a production build, set `exposeTestingApiInProductionBuild` so `next start` exposes the same API: Run these against `next dev`, where the testing API is enabled automatically. For CI with a production build, enable [`exposeTestingApiInProductionBuild`](/docs/app/api-reference/config/next-config-js/exposeTestingApiInProductionBuild) only for the test build:
```ts filename="next.config.ts" highlight={5} ```ts filename="next.config.ts" highlight={3,8}
import type { NextConfig } from 'next' import type { NextConfig } from 'next'
const exposeTestingApi = process.env.EXPOSE_TESTING_API === '1'
const nextConfig: NextConfig = { const nextConfig: NextConfig = {
cacheComponents: true, cacheComponents: true,
experimental: { exposeTestingApiInProductionBuild: true }, experimental: {
exposeTestingApiInProductionBuild: exposeTestingApi,
},
} }
export default nextConfig export default nextConfig
``` ```
Set `EXPOSE_TESTING_API=1` when running `next build`. Setting it only for `next start` does not add the testing API to an existing build.
Focus these tests on the user flows that matter most. Focus these tests on the user flows that matter most.
## Fixing a navigation that blocks ## Fixing a navigation that blocks
......
...@@ -6,6 +6,7 @@ related: ...@@ -6,6 +6,7 @@ related:
title: Next Steps title: Next Steps
description: Learn about other behavior changes when Cache Components is enabled. description: Learn about other behavior changes when Cache Components is enabled.
links: links:
- app/guides/optimizing-the-static-shell
- app/guides/instant-navigation - app/guides/instant-navigation
- app/getting-started/caching - app/getting-started/caching
- app/guides/preserving-ui-state - app/guides/preserving-ui-state
...@@ -21,7 +22,7 @@ The migration is driven by **instant navigation validation**. With Cache Compone ...@@ -21,7 +22,7 @@ The migration is driven by **instant navigation validation**. With Cache Compone
## Use the adoption skill (recommended) ## Use the adoption skill (recommended)
The [`next-cache-components-adoption`](https://github.com/vercel/next.js/tree/canary/skills/next-cache-components-adoption) skill drives this migration with a coding agent, one feature at a time, checking in at every feature boundary. It supports two modes: The [`next-cache-components-adoption`](/docs/app/guides/ai-agents#next-cache-components-adoption) skill drives this migration with a coding agent, one feature at a time, checking in at every feature boundary. It supports two modes:
- **Incremental.** Opens a single mechanical PR that opts every route out of validation, then ships each feature as a follow-up PR. This automates the [Adopting incrementally](#adopting-incrementally) flow below. - **Incremental.** Opens a single mechanical PR that opts every route out of validation, then ships each feature as a follow-up PR. This automates the [Adopting incrementally](#adopting-incrementally) flow below.
- **Direct.** Adopts every route in place on one branch. - **Direct.** Adopts every route in place on one branch.
......
...@@ -23,6 +23,22 @@ With [Cache Components](/docs/app/getting-started/caching) and [Partial Prefetch ...@@ -23,6 +23,22 @@ With [Cache Components](/docs/app/getting-started/caching) and [Partial Prefetch
The shared App Shell does not include URL data that varies by destination, such as [`searchParams`](/docs/app/api-reference/file-conventions/page#searchparams-optional) and [`params`](/docs/app/api-reference/file-conventions/page#params-optional). Set `prefetch={true}` on a link to resolve cached content that depends on its [URL data](/docs/app/glossary#url-data) before navigation instead of streaming that content after navigation. The shared App Shell does not include URL data that varies by destination, such as [`searchParams`](/docs/app/api-reference/file-conventions/page#searchparams-optional) and [`params`](/docs/app/api-reference/file-conventions/page#params-optional). Set `prefetch={true}` on a link to resolve cached content that depends on its [URL data](/docs/app/glossary#url-data) before navigation instead of streaming that content after navigation.
## Use the optimizer skill (recommended)
The [`next-partial-prefetching-optimizer`](/docs/app/guides/ai-agents#next-partial-prefetching-optimizer) skill applies this guide with a coding agent. It defines the UI that should be ready for a selected link in an [`instant()` test](/docs/app/guides/instant-navigation#prevent-regressions-with-e2e-tests), proves the current behavior, and works the test to green.
Install the skill:
```bash filename="Terminal"
npx skills add vercel/next.js --skill next-partial-prefetching-optimizer
```
Then give the agent the source, destination, and UI that should be available immediately:
```prompt
Make the search results instant when navigating from / to /search?q=react. Use the next-partial-prefetching-optimizer Skill.
```
This guide assumes [Cache Components](/docs/app/getting-started/caching) with [`partialPrefetching`](/docs/app/api-reference/config/next-config-js/partialPrefetching) enabled: This guide assumes [Cache Components](/docs/app/getting-started/caching) with [`partialPrefetching`](/docs/app/api-reference/config/next-config-js/partialPrefetching) enabled:
```ts filename="next.config.ts" highlight={4,5} ```ts filename="next.config.ts" highlight={4,5}
......
This diff is collapsed.
...@@ -797,6 +797,8 @@ The trigger is **your code**: async work, non-deterministic output, or runtime d ...@@ -797,6 +797,8 @@ The trigger is **your code**: async work, non-deterministic output, or runtime d
The key decisions are **what to cache** and **where to place Suspense boundaries**. Cache what you can with [`"use cache"`](/docs/app/api-reference/directives/use-cache) to grow the static shell. Push dynamic access down to the components that need it, and wrap those in `<Suspense>`. Everything else becomes part of the shell. The key decisions are **what to cache** and **where to place Suspense boundaries**. Cache what you can with [`"use cache"`](/docs/app/api-reference/directives/use-cache) to grow the static shell. Push dynamic access down to the components that need it, and wrap those in `<Suspense>`. Everything else becomes part of the shell.
For a step-by-step workflow that applies these patterns to an existing route, see [Optimizing the static shell](/docs/app/guides/optimizing-the-static-shell).
## Further reading ## Further reading
- [RSC Explorer](https://rscexplorer.dev/) - interactive tool to explore the component payload format and see how React reconstructs the tree from streamed chunks - [RSC Explorer](https://rscexplorer.dev/) - interactive tool to explore the component payload format and see how React reconstructs the tree from streamed chunks
......
...@@ -138,7 +138,7 @@ When the UI is frozen, click **Resume** to let the current navigation finish. Th ...@@ -138,7 +138,7 @@ When the UI is frozen, click **Resume** to let the current navigation finish. Th
## Testing instant navigation ## Testing instant navigation
The `@next/playwright` package exports an `instant()` helper that holds back dynamic content while the callback runs against the instant UI. See the [guide](/docs/app/guides/instant-navigation#prevent-regressions-with-e2e-tests) for a full example. The `@next/playwright` package exports an `instant()` helper that holds back dynamic content while the callback runs against the instant UI. The testing API is available automatically in development. For a production build, enable [`experimental.exposeTestingApiInProductionBuild`](/docs/app/api-reference/config/next-config-js/exposeTestingApiInProductionBuild) in the test build. See the [guide](/docs/app/guides/instant-navigation#prevent-regressions-with-e2e-tests) for a full example.
```typescript ```typescript
import { instant } from '@next/playwright' import { instant } from '@next/playwright'
......
---
title: exposeTestingApiInProductionBuild
description: Expose the Instant Navigation testing API in production builds for end-to-end tests.
version: experimental
related:
title: Related
description: Learn how to inspect and test instant navigation.
links:
- app/api-reference/file-conventions/route-segment-config/instant
- app/guides/instant-navigation
---
`experimental.exposeTestingApiInProductionBuild` includes the Instant Navigation testing API in a production build. The [`instant()` helper from `@next/playwright`](/docs/app/guides/instant-navigation#prevent-regressions-with-e2e-tests) uses this API to pause request-time content while an end-to-end test asserts on the UI available immediately.
Enable the option only for a dedicated test build:
```ts filename="next.config.ts" switcher highlight={3,8}
import type { NextConfig } from 'next'
const exposeTestingApi = process.env.EXPOSE_TESTING_API === '1'
const nextConfig: NextConfig = {
cacheComponents: true,
experimental: {
exposeTestingApiInProductionBuild: exposeTestingApi,
},
}
export default nextConfig
```
```js filename="next.config.js" switcher highlight={1,7}
const exposeTestingApi = process.env.EXPOSE_TESTING_API === '1'
/** @type {import('next').NextConfig} */
const nextConfig = {
cacheComponents: true,
experimental: {
exposeTestingApiInProductionBuild: exposeTestingApi,
},
}
module.exports = nextConfig
```
Set the condition when running `next build`, then serve that build with `next start`:
```bash filename="Terminal"
EXPOSE_TESTING_API=1 pnpm build
pnpm start
```
Setting the condition only for `next start` does not add the testing API to an existing build.
## Reference
| Value | Behavior |
| ---------------- | --------------------------------------------------------------------- |
| `false` or unset | Excludes the testing API from production builds. This is the default. |
| `true` | Includes the testing API in the production build. |
The option requires [`cacheComponents`](/docs/app/api-reference/config/next-config-js/cacheComponents). Development builds expose the testing API automatically when Cache Components is enabled.
> **Good to know:** Do not enable this option for a user-facing production deployment. Restrict it to local production builds, preview deployments, or other environments used for end-to-end tests.
## Version History
| Version | Changes |
| --------- | ------------------------------------------------------------ |
| `v16.2.0` | `experimental.exposeTestingApiInProductionBuild` introduced. |
...@@ -84,6 +84,10 @@ Docs can link to a canonical skill, but an unmerged skill revision isn't part of ...@@ -84,6 +84,10 @@ Docs can link to a canonical skill, but an unmerged skill revision isn't part of
The runner then adds a third `skills` variant for that fixture. It installs the listed directories from the local `skills/` folder before the coding agent starts, while keeping the prompt, app, and assertions identical. It does not also inject the `agents-md` instruction: the skill treatment measures whether the skill itself leads the agent to the canonical bundled guide. The optional timeout lets end-to-end workflows run longer than the 12-minute default. Fixtures without an entry continue to run only `baseline` and `agents-md`. The runner then adds a third `skills` variant for that fixture. It installs the listed directories from the local `skills/` folder before the coding agent starts, while keeping the prompt, app, and assertions identical. It does not also inject the `agents-md` instruction: the skill treatment measures whether the skill itself leads the agent to the canonical bundled guide. The optional timeout lets end-to-end workflows run longer than the 12-minute default. Fixtures without an entry continue to run only `baseline` and `agents-md`.
Browser-dependent fixtures declare `@playwright/test` in `dependencies` or
`devDependencies` in their `package.json`. The runner detects that dependency
and installs Chromium and its system libraries before the agent starts.
A run takes ~2–5 min. To validate a fixture without executing: A run takes ~2–5 min. To validate a fixture without executing:
```bash ```bash
......
...@@ -14,6 +14,10 @@ ...@@ -14,6 +14,10 @@
"publish": false, "publish": false,
"timeout": 1800 "timeout": 1800
}, },
"agent-050-optimize-static-shell": {
"skills": ["next-cache-components-optimizer"],
"timeout": 7200
},
"agent-054-cache-components-empty-static-params": { "agent-054-cache-components-empty-static-params": {
"skills": ["next-cache-components-adoption"], "skills": ["next-cache-components-adoption"],
"timeout": 1800 "timeout": 1800
......
/**
* Optimize a static shell
*
* This is intentionally not the team-settings example from the guide. The
* agent must apply the same framework reasoning to a release route with a
* request-specific layout control, reusable file-backed data, URL-dependent
* live data, and both hard and soft navigation contracts.
*/
import { expect, test } from 'vitest'
import { existsSync, readFileSync, readdirSync, statSync } from 'fs'
import { join } from 'path'
import { environment, transcript } from '@vercel/agent-eval/eval'
const IGNORE_DIRS = new Set([
'.git',
'.next',
'node_modules',
'dist',
'build',
'coverage',
])
function readSourceFiles(dir: string): string[] {
if (!existsSync(dir)) return []
return readdirSync(dir).flatMap((entry) => {
if (IGNORE_DIRS.has(entry)) return []
const path = join(dir, entry)
if (statSync(path).isDirectory()) return readSourceFiles(path)
if (entry === 'EVAL.ts' || !/\.(ts|tsx|js|jsx)$/.test(entry)) return []
return readFileSync(path, 'utf-8')
})
}
const source = readSourceFiles(process.cwd()).join('\n')
const testSource = readSourceFiles(join(process.cwd(), 'tests')).join('\n')
const releaseDataSource = readFileSync(
join(process.cwd(), 'lib/releases.ts'),
'utf-8'
)
test('removes the route opt-out while keeping Cache Components enabled', () => {
const config = readFileSync(join(process.cwd(), 'next.config.ts'), 'utf-8')
expect(config).toMatch(/cacheComponents\s*:\s*true/)
expect(source).not.toMatch(/export\s+(?:const|var|let)\s+instant\s*=\s*false/)
})
test('covers direct visits and client navigations with instant()', () => {
expect(testSource).toMatch(/from\s+['"]@next\/playwright['"]/)
expect(testSource).toMatch(/\binstant\s*\(/)
expect(testSource).toMatch(/\.click\s*\(/)
expect(testSource).toMatch(/\.goto\s*\(/)
})
test('asserts the complete instant shell contract', () => {
expect(testSource).toMatch(/release-shell/)
expect(testSource).toMatch(/release-heading/)
expect(testSource).toMatch(/launch-checklist/)
expect(testSource).toMatch(/viewer-skeleton/)
expect(testSource).toMatch(/rollout-skeleton/)
expect(testSource).toMatch(/viewer-controls/)
expect(testSource).toMatch(/live-rollout/)
})
test('caches the reusable checklist without replacing its data source', () => {
expect(source).toMatch(/['"]use cache['"]/)
expect(releaseDataSource).toMatch(/\breadFile\b/)
expect(releaseDataSource).not.toMatch(/import\s+launchChecklist\s+from/)
})
test('puts the intended reusable UI in the static shell', async () => {
await expect(environment).toSatisfyCriterion(
`The final /releases/aurora implementation keeps the release frame/navigation, Release operations heading, and launch checklist in the static shell. Only the existing launch-checklist read is cached, and the implementation preserves that read rather than replacing it with a build-time import. The page or a high-level boundary is not replaced with an empty or duplicate full-page fallback.`
)
})
test('keeps request-time UI behind focused loading states', async () => {
await expect(environment).toSatisfyCriterion(
`The viewer cookie and live rollout remain request-time and are not placed in a public cache. The existing viewer and rollout loading states are reused in focused Suspense boundaries. Under the instant() lock, both skeletons are visible while viewer controls and live rollout are absent. After release, the request-time UI renders and replaces those loading states.`
)
})
test('preserves all completed release variants', async () => {
await expect(transcript).toSatisfyCriterion(
`Using the existing production rig, the agent executed completed-route parity checks rather than only inspecting source or the static shell. The Aurora rollout still renders 72 percent and Global, the Nebula release still renders 18 percent and Europe, and an unknown release still renders the not-found UI.`
)
})
test('preserves the request-specific viewer cookie', async () => {
await expect(transcript).toSatisfyCriterion(
`Using the existing production rig, the agent verified that viewer controls render the viewer supplied through the rig's optional viewer cookie after the instant() lock releases. Merely retaining cookie-reading source code does not satisfy this criterion.`
)
})
test('proved the unlocked baseline and trustworthy RED', async () => {
await expect(transcript).toSatisfyCriterion(
`The agent reused instant-nav.rig.md and its production Playwright command instead of creating another server lifecycle. Before changing production code, it confirmed the complete intended UI rendered once without instant(), then observed a locked RED on the unfixed route for the intended missing shell behavior. A timeout before navigation, missing fixture data, stale build, or unavailable selector does not satisfy this criterion.`
)
})
test('reached GREEN and ran the complete production suite', async () => {
await expect(transcript).toSatisfyCriterion(
`After applying the optimization, the agent ran the required direct-visit and client-navigation instant() contracts successfully on the production rig. It also ran the complete in-scope production command with no required test skipped, and verified completed content after the lock released. Merely writing the tests, passing a filtered subset, or obtaining a successful build does not satisfy this criterion.`
)
})
test('completed the bounded differential', async () => {
await expect(transcript).toSatisfyCriterion(
`After reaching GREEN, the agent reverted only the implementation fix and observed every intended instant() contract return to RED. It then reapplied the fix and observed final GREEN. It ran one conclusive check per gate and repeated a build or test only after changing code or observing an infrastructure failure, not as an arbitrary stress or flake loop. Merely describing the differential or changing the tests during it does not satisfy this criterion.`
)
})
Optimize the `/releases/aurora` route for both direct visits and client navigation from the home page. The release frame, heading, and reusable launch checklist should be ready immediately. The current viewer controls and live rollout details must stay request-time, using the loading states already in the app. Preserve the existing data sources and freshness behavior. A production `instant()` test rig is already documented in `instant-nav.rig.md`; reuse it instead of creating another server lifecycle. Preserve the result with regression coverage and finish the production verification.
After the instant checks release, use the same production rig to verify the completed route behavior for Aurora (72 percent and Global), Nebula (18 percent and Europe), and an unknown release (not-found UI). Also verify that the viewer controls render the viewer supplied through the rig's optional `viewer` cookie.
import type { ReactNode } from 'react'
export default function RootLayout({ children }: { children: ReactNode }) {
return (
<html lang="en">
<body>{children}</body>
</html>
)
}
import Link from 'next/link'
export default function HomePage() {
return (
<main>
<h1>Launch control</h1>
<p>Monitor active releases and production rollouts.</p>
<Link href="/releases/aurora">Open Aurora release</Link>
</main>
)
}
import type { ReactNode } from 'react'
import { getCurrentViewer } from '@/lib/releases'
import { ViewerControls } from './viewer-controls'
export default async function ReleaseLayout({
children,
}: {
children: ReactNode
}) {
const viewer = await getCurrentViewer()
return (
<section data-testid="release-shell">
<header>
<a href="/">Launch control</a>
<nav aria-label="Release">
<a href="#overview">Overview</a>
<a href="#checks">Checks</a>
</nav>
<ViewerControls viewer={viewer} />
</header>
{children}
</section>
)
}
import {
getLaunchChecklist,
getLiveRollout,
isKnownRelease,
} from '@/lib/releases'
import { LaunchChecklist, LiveRollout } from './release-panels'
import { notFound } from 'next/navigation'
export const instant = false
export default async function ReleasePage({
params,
}: PageProps<'/releases/[release]'>) {
const { release } = await params
if (!isKnownRelease(release)) {
notFound()
}
const [checklist, rollout] = await Promise.all([
getLaunchChecklist(),
getLiveRollout(release),
])
return (
<main>
<h1 data-testid="release-heading">Release operations</h1>
<LaunchChecklist checklist={checklist} />
<LiveRollout rollout={rollout} />
</main>
)
}
import type { ReleaseChecklist, Rollout } from '@/lib/releases'
export function LaunchChecklist({
checklist,
}: {
checklist: ReleaseChecklist
}) {
return (
<section id="checks" data-testid="launch-checklist">
<h2>{checklist.title}</h2>
<ul>
{checklist.items.map((item) => (
<li key={item}>{item}</li>
))}
</ul>
</section>
)
}
export function LaunchChecklistSkeleton() {
return (
<section aria-label="Loading launch checklist">
<h2>Launch checklist</h2>
<p>Loading checks…</p>
</section>
)
}
export function LiveRollout({ rollout }: { rollout: Rollout }) {
return (
<section id="overview" data-testid="live-rollout">
<h2>Live rollout</h2>
<p>{rollout.percent}% deployed</p>
<p>{rollout.region}</p>
</section>
)
}
export function LiveRolloutSkeleton() {
return (
<section aria-label="Loading live rollout" data-testid="rollout-skeleton">
<h2>Live rollout</h2>
<p>Loading current deployment…</p>
</section>
)
}
export function ViewerControls({ viewer }: { viewer: string }) {
return (
<div data-testid="viewer-controls">
Viewing as <strong>{viewer}</strong>
</div>
)
}
export function ViewerControlsSkeleton() {
return (
<div aria-label="Loading viewer controls" data-testid="viewer-skeleton">
Loading viewer…
</div>
)
}
{
"title": "Launch checklist",
"items": [
"Error budget reviewed",
"Rollback owner assigned",
"Support briefed"
]
}
# instant-nav rig: release fixture
- BUILD: `EXPOSE_TESTING_API=1 npm run build`
- EXPOSE: `EXPOSE_TESTING_API=1` enables `experimental.exposeTestingApiInProductionBuild` during the measured build
- RUN: `npm run test:instant -- tests/release-shell.spec.ts`; Playwright's existing `webServer` owns `next start` on port 3311
- TEST USER: public; no authentication; an optional `viewer` cookie changes the viewer label
- DRIFT: none known
- CONTRACTS: `/releases/aurora` direct visit and the `Open Aurora release` Link from `/`; instant UI is the release frame, heading, and launch checklist; viewer controls and live rollout stay deferred
- LOOP: run the focused command once at each baseline, RED, GREEN, parity, and differential gate; edit between gates; do not start or stop the server manually
- LIVENESS: n/a; Playwright starts the freshly built local artifact and waits for its URL
- WALLS: do not add another Playwright config, hard-code a browser executable, use port 3000, or stress-run a conclusive result
import { readFile } from 'node:fs/promises'
import { cookies } from 'next/headers'
import { connection } from 'next/server'
export type ReleaseChecklist = {
title: string
items: string[]
}
export type Rollout = {
percent: number
region: string
}
export function isKnownRelease(release: string): boolean {
return release === 'aurora' || release === 'nebula'
}
export async function getCurrentViewer(): Promise<string> {
const cookieStore = await cookies()
return cookieStore.get('viewer')?.value ?? 'Release engineer'
}
export async function getLaunchChecklist(): Promise<ReleaseChecklist> {
const source = await readFile(
new URL('../data/launch-checklist.json', import.meta.url),
'utf8'
)
return JSON.parse(source) as ReleaseChecklist
}
export async function getLiveRollout(release: string): Promise<Rollout> {
await connection()
return {
percent: release === 'aurora' ? 72 : 18,
region: release === 'aurora' ? 'Global' : 'Europe',
}
}
/// <reference types="next" />
/// <reference types="next/image-types/global" />
// NOTE: This file should not be edited
// see https://nextjs.org/docs/app/api-reference/config/typescript for more information.
import type { NextConfig } from 'next'
const exposeTestingApi = process.env.EXPOSE_TESTING_API === '1'
const nextConfig: NextConfig = {
cacheComponents: true,
experimental: {
exposeTestingApiInProductionBuild: exposeTestingApi,
},
}
export default nextConfig
{
"private": true,
"type": "module",
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"test:instant": "EXPOSE_TESTING_API=1 npm run build && playwright test"
},
"dependencies": {
"next": "^16",
"react": "19.1.0",
"react-dom": "19.1.0"
},
"devDependencies": {
"@next/playwright": "canary",
"@playwright/test": "1.61.0",
"@types/node": "^20",
"@types/react": "^19",
"@types/react-dom": "^19",
"typescript": "^5",
"vitest": "^3.1.3",
"@vitejs/plugin-react": "^4.4.1",
"vite-tsconfig-paths": "^5.1.4"
}
}
import { defineConfig } from '@playwright/test'
const port = Number(process.env.PORT ?? 3311)
const baseURL = process.env.BASE_URL ?? `http://127.0.0.1:${port}`
export default defineConfig({
testDir: './tests',
fullyParallel: false,
retries: 0,
workers: 1,
reporter: [['list']],
use: {
baseURL,
trace: 'off',
},
webServer: {
command: `npm run start -- --port ${port}`,
url: baseURL,
reuseExistingServer: false,
timeout: 120_000,
},
})
const port = Number(process.env.PORT ?? 3311)
const baseURL = process.env.BASE_URL ?? `http://127.0.0.1:${port}`
export function testUrl(path: string): string {
return new URL(path, baseURL).toString()
}
export const origin = new URL(baseURL).origin
{
"compilerOptions": {
"target": "ES2017",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "react-jsx",
"incremental": true,
"plugins": [
{
"name": "next"
}
],
"paths": {
"@/*": ["./*"]
}
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
"exclude": ["node_modules", "EVAL.ts"]
}
# Real-app patterns
The rest of this skill models a single linear `layout → page` tree. Production App Router routes add **parallel routes, shared layout UI, and auth gates**, which is where most of the real static-shell work happens. These patterns bridge that gap. Read the skill's `SKILL.md` first.
## Parallel routes: each slot is its own boundary
Instant validation treats every parallel-route slot below the shared layout as an **independent** navigation boundary. Consequences:
- **Each `@slot` needs its own `<Suspense>`** around its dynamic reads; a boundary in one slot does not cover another.
- **An uncovered dynamic read in any slot blocks the whole navigation.** A perfect `@content` does not help if `@sidebar` awaits a session at the top.
- **A slot that renders `null` (e.g. `default.tsx`) is shell-safe**: it is static and performs no reads. Slots that do not re-render for this navigation cost nothing.
```
[tenant]/layout.tsx (shared: already mounted on a soft navigation; not re-rendered)
├ @content → settings/layout → billing/page ← guard each slot's dynamic reads…
├ @sidebar → side nav ← …here too (independent boundary)
└ @header → default.tsx → null ← free
```
## Client-rendered slot routing is not part of the soft-navigation re-render
A common pattern: a stable shared layout renders `@header`/`@sidebar` through a **client** component that swaps slot content based on `usePathname()`. On a soft navigation, Next.js only re-renders the **server** segments that changed below the shared layout; a client-component subtree is not part of that re-render. So that navigation UI neither blocks the navigation nor needs a server `<Suspense>` for it; only the server segments that actually change (e.g. `@content`) matter. It does participate in an initial load (see the caveat below).
## "Instant" is not "useful shell": the empty-shell failure mode
Validation checks that a dynamic read is **guarded by a boundary**, not that the fallback is non-empty. A `<Suspense>` with no `fallback` (or `fallback={null}`) passes validation and commits instantly, but renders a **blank** shell. If a layout and its page both `await getSession()` (your auth library's request-time read) at the top under one empty-fallback boundary, the whole frame collapses to nothing while the user waits. "Validates as instant" and "good loading experience" are different goals.
> Give every boundary a real loading skeleton, and place it low so the most real content stays in the shell. A `fallback={null}` directly above `<body>` is a deliberate empty-shell opt-out; an empty fallback lower in the tree is almost always a bug.
## The responsive-skeleton mismatch: the shell must match every breakpoint
A loading skeleton that misaligns with the loaded UI is its own bug, and it usually appears on mobile. A hand-built skeleton encodes one layout; the real component is responsive and changes shape at breakpoints, so a desktop-shaped skeleton no longer lines up once the viewport is small.
A concrete shape: a list-detail view renders a list or tree in a side panel on desktop, but collapses that panel into a single dropdown or drawer on mobile (with its own loading state). A row skeleton built for the desktop panel has nothing to align with on mobile.
The fix is the same push-down as everywhere else: **share the real responsive layout between the live render and the shell render.** One responsive component renders both (its data slots show the reused `*Skeleton` in the shell and real data after the stream), so the breakpoint switch happens once, for both renders, and there is no second desktop-only skeleton to drift.
(Same hoist rule, responsive layout included.) Verify the shell at both desktop and mobile widths against the real render at the same width.
## Deferring an auth gate / top-level `await` in a layout
A top-level `await` in a layout blocks everything below it (the most common blocker; see [Runtime data during prerendering](https://nextjs.org/docs/messages/blocking-prerender-runtime)). Auth gates are the most common real instance:
```tsx
// ❌ Before: the await + redirect at the top blocks the whole settings frame
export default async function SettingsLayout({ children }) {
const session = await getSession() // your auth library's request-time read; suspends during prerender → frame can't build
if (!session?.user) redirect(getLoginUrl())
return <Shell>{children}</Shell>
}
```
```tsx
// ✅ After: render children unconditionally; move the gate into a Suspense child
import { Suspense } from 'react'
export default function SettingsLayout({ children }) {
return (
<Shell>
<Suspense fallback={null}>
<AuthGate />
</Suspense>
{children}
</Shell>
)
}
async function AuthGate() {
const session = await getSession() // the session read suspends during prerender…
if (!session?.user) redirect(getLoginUrl()) // …so redirect() never runs at build time
return null
}
```
The shell prerenders as if authorized (the session read suspends before `redirect()` is reached, so the redirect only happens at request time), and `{children}` is now in the shell instead of behind the gate. (`fallback={null}` is correct here: `AuthGate` renders nothing on success.)
## Initial-load shell vs soft-navigation shell
The `../test-template.md` specs drive a `<Link>` click for soft navigations and `page.goto()` for initial loads. The two shells can differ for the same route:
> **The initial-load shell can show less than the soft-navigation shell when a layout above the shared boundary awaits un-enumerated `params`/`searchParams`.** An initial load re-runs every layout from the root; if a parent layout does `await props.params` and that segment has no `generateStaticParams`, the param suspends on the initial load and its whole subtree drops out of the shell. A soft navigation does not re-render that parent and already has the params. Symptom: an element present after a `<Link>` click is missing after `goto`.
To assert the soft-navigation shell, drive a real `<Link>` click (through menus if necessary). Use `page.goto()` inside `instant()` to assert the initial-load shell, or when no parent above the shared boundary awaits un-enumerated params, in which case the two coincide.
## Edge cases
- **A `React.cache` (or custom memoization) wrapper around `cookies()`/`headers()` still suspends.** Memoizing the call does not make it shell-safe: the underlying request read still returns a pending promise during prerender. Only the **`use cache`** directive, keyed on static or param inputs, puts data in the shell.
- **Playwright cannot see a `display: contents` or fragment fallback.** Such a fallback reads as hidden, so `instant()` assertions cannot `toBeVisible()` it. Give fallbacks a real wrapper element with a `data-testid`.
...@@ -44,9 +44,11 @@ self-validating test variant when deferred content exists. ...@@ -44,9 +44,11 @@ self-validating test variant when deferred content exists.
7. **Renders for the test user**: under that user's flags, plan, role, and data. 7. **Renders for the test user**: under that user's flags, plan, role, and data.
8. **Conditional redirects accounted for**: assert at the route's real destination for that user. 8. **Conditional redirects accounted for**: assert at the route's real destination for that user.
9. **Real selector**: a `data-testid` on a known static-shell node, not a guessed `role`/`name`. 9. **Real selector**: a `data-testid` on a known static-shell node, not a guessed `role`/`name`.
10. **Visible marker**: not `display:none`, off-screen, or inside a hover overlay; for lists, 10. **Committed marker**: assert a DOM node after the client subtree commits, not text searched in
target `.filter({ visible: true }).first()`. the RSC response. Client Component text may not appear in the response bytes.
11. **Fresh build under test**: the deployment being measured contains the latest commit, not a 11. **Visible marker**: not `display:none`, `display: contents`, a fragment, off-screen, or inside a
hover overlay; for lists, target `.filter({ visible: true }).first()`.
12. **Fresh build under test**: the deployment being measured contains the latest commit, not a
build URL still serving the previous deploy. build URL still serving the previous deploy.
## Taxonomy: red for the wrong reason ## Taxonomy: red for the wrong reason
...@@ -76,7 +78,7 @@ reason; the rig file's DRIFT list says which rows apply to your app. ...@@ -76,7 +78,7 @@ reason; the rig file's DRIFT list says which rows apply to your app.
that no element actually had, on a list page whose CI account had no rows. → checks 7, 9. Fix: a that no element actually had, on a list page whose CI account had no rows. → checks 7, 9. Fix: a
`data-testid` on a real static-shell node. `data-testid` on a real static-shell node.
- **Hidden marker**: the testid sat first on a `hidden sm:block` hover-overlay link, then on an - **Hidden marker**: the testid sat first on a `hidden sm:block` hover-overlay link, then on an
off-screen carousel card; Playwright resolved the element but reported it hidden. → check 10. off-screen carousel card; Playwright resolved the element but reported it hidden. → check 11.
Fix: an always-visible node; for lists, `.filter({ visible: true }).first()`. Fix: an always-visible node; for lists, `.filter({ visible: true }).first()`.
## Differential check (capture in the PR) ## Differential check (capture in the PR)
...@@ -128,9 +130,9 @@ the marker; a retry masks the regression the guard exists to catch. The only leg ...@@ -128,9 +130,9 @@ the marker; a retry masks the regression the guard exists to catch. The only leg
`instant()` works by setting a cookie (`next-instant-navigation-testing`) that lock code inside the `instant()` works by setting a cookie (`next-instant-navigation-testing`) that lock code inside the
build reads. It does not throw when that lock code is absent; it only throws on nested calls or an build reads. It does not throw when that lock code is absent; it only throws on nested calls or an
unknown base URL. If the build was produced without the testing API unknown base URL. If the build was produced without the testing API
(`experimental.exposeTestingApiInProductionBuild`), the cookie is ignored, the navigation runs ([`experimental.exposeTestingApiInProductionBuild`](https://nextjs.org/docs/app/api-reference/config/next-config-js/exposeTestingApiInProductionBuild)),
normally, and the `instant()` test passes vacuously. A green `instant()` test is only meaningful if the cookie is ignored, the navigation runs normally, and the `instant()` test passes vacuously. A
the lock engaged. green `instant()` test is only meaningful if the lock engaged.
Two defenses; use both: Two defenses; use both:
......
...@@ -35,8 +35,8 @@ the process listening on the recorded port before the next build. ...@@ -35,8 +35,8 @@ the process listening on the recorded port before the next build.
### Testing API ### Testing API
An `instant()` test against a production build requires An `instant()` test against a production build requires
`experimental.exposeTestingApiInProductionBuild`. Gate it so real production [`experimental.exposeTestingApiInProductionBuild`](https://nextjs.org/docs/app/api-reference/config/next-config-js/exposeTestingApiInProductionBuild).
builds do not expose the API: Gate it so real production builds do not expose the API:
```ts filename="next.config.ts" highlight={3,8-10} ```ts filename="next.config.ts" highlight={3,8-10}
import type { NextConfig } from 'next' import type { NextConfig } from 'next'
...@@ -72,16 +72,21 @@ and reporters. The suite must import `instant()` from `@next/playwright`. If ...@@ -72,16 +72,21 @@ and reporters. The suite must import `instant()` from `@next/playwright`. If
the dependencies are absent, install `@next/playwright` on the same release the dependencies are absent, install `@next/playwright` on the same release
line as the project's `next`, alongside `@playwright/test`. line as the project's `next`, alongside `@playwright/test`.
For a local rig, a typical sequence is: Prefer an existing Playwright `webServer` configuration to own the local
server lifecycle. Ensure its command serves the production build with
`next start`. With `webServer` managing startup and cleanup, run the build and
test commands without starting another server manually:
```bash filename="Terminal" ```bash filename="Terminal"
EXPOSE_TESTING_API=1 pnpm build EXPOSE_TESTING_API=1 pnpm build
pnpm start --port 3000
BASE_URL=http://localhost:3000 pnpm playwright test tests/static-shell.spec.ts BASE_URL=http://localhost:3000 pnpm playwright test tests/static-shell.spec.ts
``` ```
Adapt the script names and port to the project. Keep the production server If the rig does not use `webServer`, start `pnpm start --port 3000` in a
running while the test command executes. Follow the public separate terminal after the build, keep it running during the test command,
and stop it afterward. Use only one server lifecycle for the measured app.
Adapt the script names and port to the project. Follow the public
[`instant()` testing pattern](https://nextjs.org/docs/app/guides/instant-navigation#prevent-regressions-with-e2e-tests): use `page.goto()` for an initial-load [`instant()` testing pattern](https://nextjs.org/docs/app/guides/instant-navigation#prevent-regressions-with-e2e-tests): use `page.goto()` for an initial-load
contract and click the real `<Link>` for a client-navigation contract. contract and click the real `<Link>` for a client-navigation contract.
...@@ -171,3 +176,7 @@ Before recording the static-shell contract: ...@@ -171,3 +176,7 @@ Before recording the static-shell contract:
Fix the rig before interpreting an optimizer failure. A missing testing API, Fix the rig before interpreting an optimizer failure. A missing testing API,
stale deployment, unreachable target, or wrong test state is an environment stale deployment, unreachable target, or wrong test state is an environment
failure rather than evidence that the shell blocks. failure rather than evidence that the shell blocks.
Once the rig produces a conclusive result, continue to the next workflow gate.
Do not repeat the same build or test to look for flakiness unless two observed
results conflict.
...@@ -6,6 +6,10 @@ Ship one test per navigation type you are guarding: under `instant()`, assert th ...@@ -6,6 +6,10 @@ Ship one test per navigation type you are guarding: under `instant()`, assert th
destination's static shell appears. `instant()` gates dynamic data, so a correctly instant route destination's static shell appears. `instant()` gates dynamic data, so a correctly instant route
commits its shell under the lock and a blocking route does not. `instant()` is a ruler, not a commits its shell under the lock and a blocking route does not. `instant()` is a ruler, not a
stopwatch: do not add custom timeouts or timing races (see `reference/red-test-robustness.md`). stopwatch: do not add custom timeouts or timing races (see `reference/red-test-robustness.md`).
Keep each route and navigation type in its own focused test. Do not loop over several routes or
aggregate their readiness results in one test; focused tests can still run serially in one browser
worker.
Whether the marker is the right one (rendering for the test user, not flag-gated, not redirected Whether the marker is the right one (rendering for the test user, not flag-gated, not redirected
away, not guessed) is established at authoring time with the unlocked baseline scaffold below away, not guessed) is established at authoring time with the unlocked baseline scaffold below
(phase B, the C-gate), not by additional assertions in the shipped test. (phase B, the C-gate), not by additional assertions in the shipped test.
...@@ -58,9 +62,13 @@ is shown only for brevity; like the marker, the trigger must reliably resolve fo ...@@ -58,9 +62,13 @@ is shown only for brevity; like the marker, the trigger must reliably resolve fo
## Initial load (hard navigation) ## Initial load (hard navigation)
Drive `page.goto()` inside `instant()` with the `baseURL` option. The served document is the Drive `page.goto()` inside `instant()` with the `baseURL` option. The document response contains
route's prerendered static shell. `baseURL` is required because `page` is still `about:blank` when the route's prerendered static shell, but Playwright assertions run after hydration. A Client
`instant()` runs (`resolveURL` falls back to `page.url()` only when no `baseURL` is passed). Component that can resolve without request-time server content may already be visible. Choose a
shell marker that remains valid after hydration instead of a prerender fallback that hydration
replaces immediately. `baseURL` is required because `page` is still `about:blank` when `instant()`
runs (`resolveURL` falls back to `page.url()` only when no `baseURL` is passed).
Establish the session WITHOUT navigating `page` (inject `storageState`, or log in on a separate Establish the session WITHOUT navigating `page` (inject `storageState`, or log in on a separate
context/page). A login helper that navigates `page` itself defeats the measurement for a different context/page). A login helper that navigates `page` itself defeats the measurement for a different
reason: that navigation completes before `instant()` acquires the lock, so it runs unmeasured. The reason: that navigation completes before `instant()` acquires the lock, so it runs unmeasured. The
...@@ -118,9 +126,9 @@ cached. So the initial-load `toHaveCount(0)` gated half is as valid as the soft- ...@@ -118,9 +126,9 @@ cached. So the initial-load `toHaveCount(0)` gated half is as valid as the soft-
no fresh browser context and no cache-busting query param. no fresh browser context and no cache-busting query param.
The **post-release** assertion (`getByTestId('<b>-content').toBeVisible()` after the `instant()` The **post-release** assertion (`getByTestId('<b>-content').toBeVisible()` after the `instant()`
block) is soft-nav only. On an initial load the document was already emitted under the lock, so block) applies to both forms. When the lock is released, Next.js refreshes the route so deferred
nothing streams in after release; drop that assertion from the initial-load test, or content can render. For an initial load, this is a soft refresh after hydration, with a hard reload
`page.reload()` first to fetch an unlocked document. The mechanism is in fallback if the router is not ready yet. The mechanism is in
`reference/red-test-robustness.md`. `reference/red-test-robustness.md`.
## Baseline scaffold: do not ship ## Baseline scaffold: do not ship
...@@ -133,9 +141,10 @@ scaffold before the PR. ...@@ -133,9 +141,10 @@ scaffold before the PR.
**The baseline must mirror the navigation type of the test you are shipping.** Drive a `<Link>` **The baseline must mirror the navigation type of the test you are shipping.** Drive a `<Link>`
click when guarding the soft-nav shell; drive `page.goto()` when guarding the initial-load shell. click when guarding the soft-nav shell; drive `page.goto()` when guarding the initial-load shell.
The two shells can differ (`reference/real-app-patterns.md`): a click-driven baseline run against a The two shells can differ, as described in the
shipped `goto` test would confirm a marker that the `goto` path never shows, which produces exactly [initial-load and client-navigation section](https://nextjs.org/docs/app/guides/instant-navigation#prevent-regressions-with-e2e-tests). A click-driven
the false RED the C-gate exists to prevent. baseline run against a shipped `goto` test would confirm a marker that the `goto` path never shows,
which produces exactly the false RED the C-gate exists to prevent.
```ts ```ts
// soft-nav baseline: mirror the soft-nav instant() test // soft-nav baseline: mirror the soft-nav instant() test
......
...@@ -18,7 +18,7 @@ The development insights and the preservation tests are two different paths. Ins ...@@ -18,7 +18,7 @@ The development insights and the preservation tests are two different paths. Ins
## preservation gate ## preservation gate
When using test-backed preservation, the first implementation milestone is a passing flag-off `instant()` suite. Set up the production test rig, write the selected assertions, run them with `partialPrefetching` disabled, and record the command and exit status. Test-only configuration required by the rig is allowed, but until that baseline passes, do not enable `partialPrefetching` or edit the destination, cache boundaries, or Link props. Installing missing test dependencies is part of reaching the baseline, not a reason to adopt first. Use the manual path only when `rig-template.md` identifies a concrete blocker the repository cannot resolve, and record the blocker and deferred test coverage. When using test-backed preservation, the first implementation milestone is a passing flag-off `instant()` suite. Set up the production test rig, write the selected assertions, run them with `partialPrefetching` disabled, and record the command and exit status. Test-only configuration required by the rig, including [`experimental.exposeTestingApiInProductionBuild`](https://nextjs.org/docs/app/api-reference/config/next-config-js/exposeTestingApiInProductionBuild), is allowed, but until that baseline passes, do not enable `partialPrefetching` or edit the destination, cache boundaries, or Link props. Installing missing test dependencies is part of reaching the baseline, not a reason to adopt first. Use the manual path only when `rig-template.md` identifies a concrete blocker the repository cannot resolve, and record the blocker and deferred test coverage.
Talk to the user in terms of what they'll see — PRs, features, and how the app behaves after — never the insight slugs or step labels. Before you start, tell them briefly what Partial Prefetching changes: links to a route prefetch one shared App Shell, and `prefetch={true}` can also resolve cached URL-specific content. The audit determines which UI from the legacy full prefetch to preserve. Talk to the user in terms of what they'll see — PRs, features, and how the app behaves after — never the insight slugs or step labels. Before you start, tell them briefly what Partial Prefetching changes: links to a route prefetch one shared App Shell, and `prefetch={true}` can also resolve cached URL-specific content. The audit determines which UI from the legacy full prefetch to preserve.
......
...@@ -35,8 +35,8 @@ the process listening on the recorded port before the next build. ...@@ -35,8 +35,8 @@ the process listening on the recorded port before the next build.
### Testing API ### Testing API
An `instant()` test against a production build requires An `instant()` test against a production build requires
`experimental.exposeTestingApiInProductionBuild`. Gate it so real production [`experimental.exposeTestingApiInProductionBuild`](https://nextjs.org/docs/app/api-reference/config/next-config-js/exposeTestingApiInProductionBuild).
builds do not expose the API: Gate it so real production builds do not expose the API:
```ts filename="next.config.ts" highlight={3,8-10} ```ts filename="next.config.ts" highlight={3,8-10}
import type { NextConfig } from 'next' import type { NextConfig } from 'next'
...@@ -72,20 +72,31 @@ and reporters. The suite must import `instant()` from `@next/playwright`. If ...@@ -72,20 +72,31 @@ and reporters. The suite must import `instant()` from `@next/playwright`. If
the dependencies are absent, install `@next/playwright` on the same release the dependencies are absent, install `@next/playwright` on the same release
line as the project's `next`, alongside `@playwright/test`. line as the project's `next`, alongside `@playwright/test`.
For a local rig, a typical sequence is: Prefer an existing Playwright `webServer` configuration to own the local
server lifecycle. Ensure its command serves the production build with
`next start`. With `webServer` managing startup and cleanup, run the build and
test commands without starting another server manually:
```bash filename="Terminal" ```bash filename="Terminal"
EXPOSE_TESTING_API=1 pnpm build EXPOSE_TESTING_API=1 pnpm build
pnpm start --port 3000
BASE_URL=http://localhost:3000 pnpm playwright test tests/prefetch-preservation.spec.ts 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 If the rig does not use `webServer`, start `pnpm start --port 3000` in a
running while the test command executes. Follow the public separate terminal after the build, keep it running during the test command,
and stop it afterward. Use only one server lifecycle for the measured app.
Adapt the script names and port to the project. 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 [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, Link is visible, then enter `instant()`, click, wait for the destination URL,
and assert the prefetched UI. and assert the prefetched UI.
Assert a `data-testid` on a real, visible DOM node after its client subtree
commits. Do not search the RSC response for text to infer that commit, because
Client Component text might not appear in the response bytes. Do not use a
marker on `display: none`, `display: contents`, a fragment, off-screen content,
or a hover-only overlay.
### Test context ### Test context
Record the state required to reach the audited Links and destination UI: Record the state required to reach the audited Links and destination UI:
......
...@@ -90,9 +90,10 @@ prefetch budget instead of creating another rig. ...@@ -90,9 +90,10 @@ prefetch budget instead of creating another rig.
If the project has no rig, use [`rig-template.md`](rig-template.md) to discover If the project has no rig, use [`rig-template.md`](rig-template.md) to discover
and record one. The measured run must be a production build or and record one. The measured run must be a production build or
preview where `experimental.exposeTestingApiInProductionBuild` is enabled only preview where
for testing. Development can help diagnose a route, but automatic link [`experimental.exposeTestingApiInProductionBuild`](https://nextjs.org/docs/app/api-reference/config/next-config-js/exposeTestingApiInProductionBuild)
prefetching is production-only. is enabled only for testing. Development can help diagnose a route, but
automatic link prefetching is production-only.
## Prove the current behavior ## Prove the current behavior
......
...@@ -18,6 +18,12 @@ user: ...@@ -18,6 +18,12 @@ user:
Only then restore the selected contract assertions and change the Only then restore the selected contract assertions and change the
implementation. implementation.
Use a `data-testid` on a real, visible DOM node after its client subtree
commits. Do not infer that commit by searching the RSC response for text:
Client Component text might not appear in the response bytes. A marker on
`display: none`, `display: contents`, a fragment, off-screen content, or a
hover-only overlay cannot prove that the user can see the selected UI.
## What each signal rules out ## What each signal rules out
- **Destination URL wait** rules out matching the source page or clicking a - **Destination URL wait** rules out matching the source page or clicking a
...@@ -54,6 +60,9 @@ regressed. ...@@ -54,6 +60,9 @@ regressed.
- The target is URL-specific but the test user's record/query returns empty. - The target is URL-specific but the test user's record/query returns empty.
- The target is behind a flag, role, plan, locale, or experiment absent in CI. - The target is behind a flag, role, plan, locale, or experiment absent in CI.
- Auth redirects to a page where the shell selector happens to exist. - Auth redirects to a page where the shell selector happens to exist.
- The source link points to a redirect URL, so its prefetch receives the
redirect instead of the destination route tree. Point the link at its
canonical destination.
- A shared selector matches the source before the destination commits. - A shared selector matches the source before the destination commits.
- The test clicks a default link while the code change modified a different - The test clicks a default link while the code change modified a different
link to the same URL. link to the same URL.
...@@ -75,10 +84,10 @@ prop against `prefetch={true}`. ...@@ -75,10 +84,10 @@ prop against `prefetch={true}`.
## Lock engagement ## Lock engagement
`experimental.exposeTestingApiInProductionBuild` must be true on the measured [`experimental.exposeTestingApiInProductionBuild`](https://nextjs.org/docs/app/api-reference/config/next-config-js/exposeTestingApiInProductionBuild)
artifact. A marker that is absent under lock and visible after release is the must be true on the measured artifact. A marker that is absent under lock and
in-band proof that the lock engaged. A vacuous no-op cannot satisfy both visible after release is the in-band proof that the lock engaged. A vacuous
halves. no-op cannot satisfy both halves.
Never enable this flag for real production traffic. For a remote rig, verify Never enable this flag for real production traffic. For a remote rig, verify
the deployed commit before trusting RED or GREEN. the deployed commit before trusting RED or GREEN.
......
...@@ -35,8 +35,8 @@ the process listening on the recorded port before the next build. ...@@ -35,8 +35,8 @@ the process listening on the recorded port before the next build.
### Testing API ### Testing API
An `instant()` test against a production build requires An `instant()` test against a production build requires
`experimental.exposeTestingApiInProductionBuild`. Gate it so real production [`experimental.exposeTestingApiInProductionBuild`](https://nextjs.org/docs/app/api-reference/config/next-config-js/exposeTestingApiInProductionBuild).
builds do not expose the API: Gate it so real production builds do not expose the API:
```ts filename="next.config.ts" highlight={3,8-10} ```ts filename="next.config.ts" highlight={3,8-10}
import type { NextConfig } from 'next' import type { NextConfig } from 'next'
...@@ -72,16 +72,21 @@ and reporters. The suite must import `instant()` from `@next/playwright`. If ...@@ -72,16 +72,21 @@ and reporters. The suite must import `instant()` from `@next/playwright`. If
the dependencies are absent, install `@next/playwright` on the same release the dependencies are absent, install `@next/playwright` on the same release
line as the project's `next`, alongside `@playwright/test`. line as the project's `next`, alongside `@playwright/test`.
For a local rig, a typical sequence is: Prefer an existing Playwright `webServer` configuration to own the local
server lifecycle. Ensure its command serves the production build with
`next start`. With `webServer` managing startup and cleanup, run the build and
test commands without starting another server manually:
```bash filename="Terminal" ```bash filename="Terminal"
EXPOSE_TESTING_API=1 pnpm build EXPOSE_TESTING_API=1 pnpm build
pnpm start --port 3000
BASE_URL=http://localhost:3000 pnpm playwright test tests/prefetch-optimization.spec.ts BASE_URL=http://localhost:3000 pnpm playwright test tests/prefetch-optimization.spec.ts
``` ```
Adapt the script names and port to the project. Keep the production server If the rig does not use `webServer`, start `pnpm start --port 3000` in a
running while the test command executes. Follow the public separate terminal after the build, keep it running during the test command,
and stop it afterward. Use only one server lifecycle for the measured app.
Adapt the script names and port to the project. 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 [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, Link is visible, then enter `instant()`, click, wait for the destination URL,
and assert the prefetched UI. and assert the prefetched UI.
......
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