Unverified Commit 2aaa6e81 authored by Aurora Scharff's avatar Aurora Scharff Committed by GitHub

docs: preserve route behavior during Cache Components adoption (#98275)

## Summary

- Explain that removing `dynamic = 'force-dynamic'` moves a route from
full request-time rendering to Cache Components' Partial Prerendering
model, then document the choices for its request-time work.
- Preserve routes that previously used `dynamic = 'force-static'` or
`dynamic = 'error'` instead of leaving them under `instant = false`,
which can move rendering to request time and reduce prefetched UI.
- Clarify that existing `fetch` and `unstable_cache` caching can remain
in place during adoption.
- Combine the incremental checkpoint and completion coverage into one
eval that verifies both stages of the migration.
- Make the adoption skill honor an explicit incremental strategy before
continuing through a complete migration.
- Remove the unrelated `.env*` ignore and restore the existing agent-054
eval registration.

## Eval results

`agent-047-adopt-cache-components` runs the complete incremental
migration with `openai/gpt-5.6-luna` through the Codex harness. It
retains the original five checks for the first shippable checkpoint and
the original seven checks for completing the migration.

| Treatment | Result | Notes |
| --- | --- | --- |
| Baseline | 11/12 | Preserved the final behavior, but treated the work
as a fresh migration instead of explicitly continuing from the recorded
first checkpoint. |
| Guide (`AGENTS.md`) | 8/12 | Built successfully, but rewrote the
existing `unstable_cache`, changed the catalog's hourly cadence, moved
its timestamp to request time, and skipped the recorded incremental
checkpoint. |
| Adoption skill | 12/12 | Preserved both cache lifetimes and static
contracts, recorded a passing incremental checkpoint, removed the
remaining opt-outs, and completed the migration. |

## Verification

- `pnpm build`
- Luna eval runs for the baseline, guide, and adoption-skill treatments
- Prettier and ESLint checks for the changed guide, skill, and eval
files
- `git diff --check`

<!-- NEXT_JS_LLM -->
parent be2c3fdb
...@@ -46,7 +46,7 @@ Migrating an existing app by hand follows a few steps, in order: ...@@ -46,7 +46,7 @@ Migrating an existing app by hand follows a few steps, in order:
2. Decide your approach: convert every route now, or [adopt incrementally](#adopting-incrementally) by [opting routes out of validation](#opting-out-of-validation) first and converting one at a time. 2. Decide your approach: convert every route now, or [adopt incrementally](#adopting-incrementally) by [opting routes out of validation](#opting-out-of-validation) first and converting one at a time.
3. [Follow the validation errors and insights](#following-validation) it surfaces, replacing each route segment config with its Cache Components equivalent and caching uncached data with [`use cache`](/docs/app/api-reference/directives/use-cache) or wrapping runtime data in [`<Suspense>`](https://react.dev/reference/react/Suspense). The per-key sections below cover each config and API. 3. [Follow the validation errors and insights](#following-validation) it surfaces, replacing each route segment config with its Cache Components equivalent and caching uncached data with [`use cache`](/docs/app/api-reference/directives/use-cache) or wrapping runtime data in [`<Suspense>`](https://react.dev/reference/react/Suspense). The per-key sections below cover each config and API.
Your existing `fetch` and `unstable_cache` caching keeps working as a separate layer, so let the insights and errors guide what to change. Your existing `fetch` and `unstable_cache` caching keeps working. Migrating `unstable_cache` is optional and can happen later.
Some surfaces have their own steps: Some surfaces have their own steps:
...@@ -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 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. 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), [`dynamic = "error"`](#dynamic--error), [`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"
...@@ -137,10 +137,12 @@ Insights don't show up in the HTTP response. An offending route still returns `2 ...@@ -137,10 +137,12 @@ Insights don't show up in the HTTP response. An offending route still returns `2
## `dynamic = "force-dynamic"` ## `dynamic = "force-dynamic"`
**Not needed.** All pages are dynamic by default. **Remove the config.** Without Cache Components, `dynamic = 'force-dynamic'` rendered the entire route for every request and made its `fetch` requests uncached. With Cache Components, uncached data and [Request-time APIs](/docs/app/glossary#request-time-apis) already run at request time. Next.js prerenders any static or cached UI around them.
After removing the config, [follow any validation errors or insights](#following-validation) that appear.
```tsx filename="app/page.tsx" switcher ```tsx filename="app/page.tsx" switcher
// Before - No longer needed // Before
export const dynamic = 'force-dynamic' export const dynamic = 'force-dynamic'
export default function Page() { export default function Page() {
...@@ -149,7 +151,7 @@ export default function Page() { ...@@ -149,7 +151,7 @@ export default function Page() {
``` ```
```jsx filename="app/page.js" switcher ```jsx filename="app/page.js" switcher
// Before - No longer needed // Before
export const dynamic = 'force-dynamic' export const dynamic = 'force-dynamic'
export default function Page() { export default function Page() {
...@@ -158,14 +160,14 @@ export default function Page() { ...@@ -158,14 +160,14 @@ export default function Page() {
``` ```
```tsx filename="app/page.tsx" switcher ```tsx filename="app/page.tsx" switcher
// After - Just remove it // After
export default function Page() { export default function Page() {
return <div>...</div> return <div>...</div>
} }
``` ```
```jsx filename="app/page.js" switcher ```jsx filename="app/page.js" switcher
// After - Just remove it // After
export default function Page() { export default function Page() {
return <div>...</div> return <div>...</div>
} }
...@@ -173,11 +175,9 @@ export default function Page() { ...@@ -173,11 +175,9 @@ export default function Page() {
## `dynamic = "force-static"` ## `dynamic = "force-static"`
Start by removing it. When unhandled uncached or runtime data access is detected during development and build time, Next.js raises an error. Otherwise, the prerendering step automatically extracts the static HTML shell. **Remove the config and keep the route fully prerendered.** Without Cache Components, `dynamic = 'force-static'` forced the route to prerender, cached its data, and made `cookies()`, `headers()`, and `useSearchParams()` return empty values.
For uncached data access, add [`use cache`](/docs/app/api-reference/directives/use-cache) as close to the data access as possible with a long [`cacheLife`](/docs/app/api-reference/functions/cacheLife) like `'max'` to maintain cached behavior. If needed, add it at the top of the page or layout. Cache uncached data with [`use cache`](/docs/app/api-reference/directives/use-cache) and a suitable [`cacheLife`](/docs/app/api-reference/functions/cacheLife). After removing the config, Request-time APIs read actual request values. Remove those dependencies if the route must remain fully prerendered.
For runtime data access (`cookies()`, `headers()`, etc.), errors will direct you to wrap it with `<Suspense>`. Since you started by using `force-static`, you must remove the runtime data access to prevent any request time work.
```tsx filename="app/page.tsx" switcher ```tsx filename="app/page.tsx" switcher
// Before // Before
...@@ -202,7 +202,7 @@ export default async function Page() { ...@@ -202,7 +202,7 @@ export default async function Page() {
```tsx filename="app/page.tsx" switcher ```tsx filename="app/page.tsx" switcher
import { cacheLife } from 'next/cache' import { cacheLife } from 'next/cache'
// After - Use 'use cache' instead // After
export default async function Page() { export default async function Page() {
'use cache' 'use cache'
cacheLife('max') cacheLife('max')
...@@ -214,7 +214,7 @@ export default async function Page() { ...@@ -214,7 +214,7 @@ export default async function Page() {
```jsx filename="app/page.js" switcher ```jsx filename="app/page.js" switcher
import { cacheLife } from 'next/cache' import { cacheLife } from 'next/cache'
// After - Use 'use cache' instead // After
export default async function Page() { export default async function Page() {
'use cache' 'use cache'
cacheLife('max') cacheLife('max')
...@@ -223,9 +223,15 @@ export default async function Page() { ...@@ -223,9 +223,15 @@ export default async function Page() {
} }
``` ```
## `dynamic = "error"`
**Remove the config.** Without Cache Components, `dynamic = 'error'` required the route to prerender and treated `fetch` requests as cached by default. It raised an error only when uncached data or a Request-time API prevented prerendering.
After removing the config, `fetch` no longer inherits that cached default. To preserve the route's existing caching behavior, wrap those requests in [`use cache`](/docs/app/api-reference/directives/use-cache) and set their lifetime with [`cacheLife`](/docs/app/api-reference/functions/cacheLife). If the route did not rely on the default, no replacement is needed.
## `revalidate` ## `revalidate`
**Replace with `cacheLife`.** Use the `cacheLife` function to define cache duration instead of the route segment config. **Replace revalidation times greater than zero with `cacheLife`.** Without Cache Components, `revalidate` set the default revalidation time for an entire route. With Cache Components, place [`use cache`](/docs/app/api-reference/directives/use-cache) around the data or UI that should be cached, then set its lifetime with [`cacheLife`](/docs/app/api-reference/functions/cacheLife).
```tsx filename="app/page.tsx" switcher ```tsx filename="app/page.tsx" switcher
// Before // Before
...@@ -246,7 +252,7 @@ export default async function Page() { ...@@ -246,7 +252,7 @@ export default async function Page() {
``` ```
```tsx filename="app/page.tsx" switcher ```tsx filename="app/page.tsx" switcher
// After - Use cacheLife // After
import { cacheLife } from 'next/cache' import { cacheLife } from 'next/cache'
export default async function Page() { export default async function Page() {
...@@ -257,7 +263,7 @@ export default async function Page() { ...@@ -257,7 +263,7 @@ export default async function Page() {
``` ```
```jsx filename="app/page.js" switcher ```jsx filename="app/page.js" switcher
// After - Use cacheLife // After
import { cacheLife } from 'next/cache' import { cacheLife } from 'next/cache'
export default async function Page() { export default async function Page() {
...@@ -269,9 +275,13 @@ export default async function Page() { ...@@ -269,9 +275,13 @@ export default async function Page() {
> **Good to know**: If your `revalidate` value doesn't match a built-in [`cacheLife`](/docs/app/api-reference/functions/cacheLife) profile (`'seconds'`, `'minutes'`, `'hours'`, `'days'`, `'weeks'`, `'max'`), pick the closest one or define a [custom profile](/docs/app/api-reference/functions/cacheLife#custom-cache-profiles) to match your conventions. You can also [redefine a built-in profile](/docs/app/api-reference/functions/cacheLife#overriding-the-default-cache-profiles), including `default`, when its timings don't match your application's caching needs. > **Good to know**: If your `revalidate` value doesn't match a built-in [`cacheLife`](/docs/app/api-reference/functions/cacheLife) profile (`'seconds'`, `'minutes'`, `'hours'`, `'days'`, `'weeks'`, `'max'`), pick the closest one or define a [custom profile](/docs/app/api-reference/functions/cacheLife#custom-cache-profiles) to match your conventions. You can also [redefine a built-in profile](/docs/app/api-reference/functions/cacheLife#overriding-the-default-cache-profiles), including `default`, when its timings don't match your application's caching needs.
For `revalidate = 0`, remove the config. Uncached data already runs at request time with Cache Components. Keep data outside a `use cache` scope when it must run for every request.
## `fetchCache` ## `fetchCache`
**Not needed.** With `use cache`, all data fetching within a cached scope is automatically cached, making `fetchCache` unnecessary. **Remove the config and set caching at the data source.** Without Cache Components, `fetchCache` changed or restricted the `cache` option for every `fetch` request in a route. With Cache Components, fetches are uncached unless they run inside a `use cache` scope.
For `default-cache`, `only-cache`, or `force-cache`, wrap the data that should remain cached in [`use cache`](/docs/app/api-reference/directives/use-cache). For `default-no-store`, `only-no-store`, or `force-no-store`, leave the data outside a cache scope. If `force-no-store` previously overrode an explicit cache option, remove that option as well.
```tsx filename="app/page.tsx" switcher ```tsx filename="app/page.tsx" switcher
// Before // Before
...@@ -284,7 +294,7 @@ export const fetchCache = 'force-cache' ...@@ -284,7 +294,7 @@ export const fetchCache = 'force-cache'
``` ```
```tsx filename="app/page.tsx" switcher ```tsx filename="app/page.tsx" switcher
// After - Use 'use cache' to control caching behavior // After
export default async function Page() { export default async function Page() {
'use cache' 'use cache'
// All fetches here are cached // All fetches here are cached
...@@ -293,7 +303,7 @@ export default async function Page() { ...@@ -293,7 +303,7 @@ export default async function Page() {
``` ```
```jsx filename="app/page.js" switcher ```jsx filename="app/page.js" switcher
// After - Use 'use cache' to control caching behavior // After
export default async function Page() { export default async function Page() {
'use cache' 'use cache'
// All fetches here are cached // All fetches here are cached
...@@ -375,11 +385,11 @@ Note the persistence difference. The `fetch` Data Cache persists cached response ...@@ -375,11 +385,11 @@ Note the persistence difference. The `fetch` Data Cache persists cached response
## `unstable_cache` ## `unstable_cache`
**Replace with `use cache`.** **No change required.**
`unstable_cache` is replaced by the [`use cache`](/docs/app/api-reference/directives/use-cache) directive. `unstable_cache` continues to work with Cache Components. You can leave it in place and migrate it later.
Turn the wrapped function into a function with the `'use cache'` directive. The cache key is derived automatically from the arguments, so the key-parts array is no longer needed, and the `options` object maps to [`cacheLife`](/docs/app/api-reference/functions/cacheLife) and [`cacheTag`](/docs/app/api-reference/functions/cacheTag). If you choose to migrate it, turn the wrapped function into a function with the `'use cache'` directive. The cache key is derived automatically from the arguments, so the key-parts array is no longer needed, and the `options` object maps to [`cacheLife`](/docs/app/api-reference/functions/cacheLife) and [`cacheTag`](/docs/app/api-reference/functions/cacheTag).
```tsx filename="app/lib/data.ts" switcher ```tsx filename="app/lib/data.ts" switcher
// Before // Before
......
/** /**
* Adopt Cache Components * Complete an incremental Cache Components migration
* *
* Verifies a complete adoption rather than a single directive. The agent must * Verifies the safe first-PR checkpoint and the completed migration in one
* enable the feature, use targeted caches for reusable data, preserve * agent run.
* request-specific behavior, and create meaningful static shells instead of
* silencing blocking routes with opt-outs.
*/ */
import { expect, test } from 'vitest' import { expect, test } from 'vitest'
...@@ -35,15 +33,51 @@ function readSourceFiles(dir: string): string[] { ...@@ -35,15 +33,51 @@ function readSourceFiles(dir: string): string[] {
const source = readSourceFiles(process.cwd()).join('\n') const source = readSourceFiles(process.cwd()).join('\n')
test('enables Cache Components without route opt-outs', () => { test('enables Cache Components without incompatible segment config', () => {
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+(?:dynamic|revalidate|fetchCache)\s*=/
)
})
test('preserves routes that were explicitly static', async () => {
await expect(environment).toSatisfyCriterion(
`Cache Components is enabled. Both routes that began with an explicit static contract are fully migrated in the first PR: the catalog route that used dynamic = 'force-static' remains prerendered and eligible for full-route prefetching, and the privacy route that used dynamic = 'error' remains fully static. Neither route, nor a parent segment covering it, is left under instant = false.`
)
})
test('preserves the catalog route and data cache lifetimes', async () => {
await expect(environment).toSatisfyCriterion(
`The catalog preserves its two independent cache behaviors: the rendered route, including its catalog-check timestamp, can refresh about once per hour, while the product-list lookup can remain cached for about one day. The existing unstable_cache implementation may remain unchanged and is not needlessly migrated merely to enable Cache Components.`
)
})
test('records the first incremental migration PR before continuing', async () => {
await expect(transcript).toSatisfyCriterion(
`Before continuing to the full-app migration, the agent records a shippable first migration PR. The account route's incompatible dynamic = 'force-dynamic' export is removed without adding replacement rendering or caching code solely for that config. Its cookie greeting remains request-specific, and the route may remain under instant = false at this checkpoint. The product route may also remain explicitly opted out, but the explicitly static catalog and privacy routes are not deferred with them. The app builds at this checkpoint before the agent continues.`
)
})
test('prioritizes protected routes and verifies the result', async () => {
await expect(transcript).toSatisfyCriterion(
`Before declaring the first migration PR ready, the agent inventories incompatible route configs. It identifies routes with pre-existing force-static or dynamic-error behavior as high-priority compatibility contracts, completes those static-route migrations rather than leaving them under blanket opt-outs, and verifies them with a successful production build. It may defer the request-specific account and product routes with instant = false for later PRs. Its verification distinguishes preserved route prerendering and navigation prefetch behavior from merely preserving an inner data cache or obtaining a green build through opt-outs.`
)
})
test('completes Cache Components adoption without route opt-outs', () => {
const config = readFileSync(join(process.cwd(), 'next.config.ts'), 'utf-8') const config = readFileSync(join(process.cwd(), 'next.config.ts'), 'utf-8')
expect(config).toMatch(/cacheComponents\s*:\s*true/) expect(config).toMatch(/cacheComponents\s*:\s*true/)
expect(source).not.toMatch(/export\s+(?:const|var|let)\s+instant\s*=\s*false/) expect(source).not.toMatch(/export\s+(?:const|var|let)\s+instant\s*=\s*false/)
expect(source).not.toMatch(/TODO:\s*Cache Components adoption/)
}) })
test('removes incompatible route revalidation config', () => { test('keeps incompatible route segment config removed', () => {
expect(source).not.toMatch(/export\s+(?:const|var|let)\s+revalidate\s*=/) expect(source).not.toMatch(
/export\s+(?:const|var|let)\s+(?:dynamic|revalidate|fetchCache)\s*=/
)
}) })
test('uses explicit cache lifetime for reusable work', () => { test('uses explicit cache lifetime for reusable work', () => {
...@@ -59,7 +93,7 @@ test('preserves request-specific account behavior and a meaningful shell', async ...@@ -59,7 +93,7 @@ test('preserves request-specific account behavior and a meaningful shell', async
test('preserves the catalog cache and timestamp cadence', async () => { test('preserves the catalog cache and timestamp cadence', async () => {
await expect(environment).toSatisfyCriterion( await expect(environment).toSatisfyCriterion(
`The catalog keeps the starter route's hourly revalidation behavior after the incompatible revalidate export is removed. A page-level or data-level use-cache boundary with an equivalent cache lifetime is valid. The catalog check timestamp belongs to that same hourly result and refreshes when the cached result refreshes; it is not incorrectly required to change on every request.` `The catalog keeps its hourly route revalidation behavior and its one-day product-list cache. The catalog check timestamp belongs to the hourly cached result and refreshes when that result refreshes; it is not incorrectly required to change on every request. The existing unstable_cache implementation may remain unchanged.`
) )
}) })
...@@ -69,8 +103,8 @@ test('keeps URL-specific product work below a Suspense boundary', async () => { ...@@ -69,8 +103,8 @@ test('keeps URL-specific product work below a Suspense boundary', async () => {
) )
}) })
test('diagnosed blocking routes and completed the production migration', async () => { test('removes the remaining opt-outs and completes the production migration', async () => {
await expect(transcript).toSatisfyCriterion( await expect(transcript).toSatisfyCriterion(
`The agent enabled cacheComponents, used a production build or Next.js runtime diagnostics to discover the resulting blocking routes, fixed each route according to whether its content was reusable or request-specific, and finished with a successful production build. It did not merely add route-wide opt-outs or stop after the first green type check.` `The agent recognizes that Cache Components is already enabled and continues from the first incremental migration PR. It removes the remaining temporary opt-outs, uses a production build or Next.js runtime diagnostics to discover the account and product blockers, fixes each route according to whether its content is reusable or request-specific, and finishes with a successful production build. It does not stop after merely deleting instant = false or obtaining a green type check.`
) )
}) })
Move this storefront to Cache Components in one branch. The catalog, product pages, account greeting, and timestamps should keep their current behavior. Finish with a production build and do not leave routes opted out. Migrate this storefront to Cache Components incrementally and complete the migration.
import { cookies } from 'next/headers' import { cookies } from 'next/headers'
export const dynamic = 'force-dynamic'
export default async function AccountPage() { export default async function AccountPage() {
const cookieStore = await cookies() const cookieStore = await cookies()
const displayName = cookieStore.get('display-name')?.value ?? 'Guest' const displayName = cookieStore.get('display-name')?.value ?? 'Guest'
......
...@@ -11,7 +11,8 @@ export default function RootLayout({ children }: { children: ReactNode }) { ...@@ -11,7 +11,8 @@ export default function RootLayout({ children }: { children: ReactNode }) {
<html lang="en"> <html lang="en">
<body> <body>
<nav> <nav>
<Link href="/">Catalog</Link> <Link href="/account">Account</Link> <Link href="/">Catalog</Link> <Link href="/privacy">Privacy</Link>{' '}
<Link href="/account">Account</Link>
</nav> </nav>
{children} {children}
</body> </body>
......
import Link from 'next/link' import Link from 'next/link'
import { getProducts } from '@/lib/catalog' import { getProducts } from '@/lib/catalog'
export const dynamic = 'force-static'
export const revalidate = 3600 export const revalidate = 3600
export default async function CatalogPage() { export default async function CatalogPage() {
......
export const dynamic = 'error'
export default function PrivacyPage() {
return (
<main>
<h1>Privacy</h1>
<p>We only use account data to personalize your experience.</p>
</main>
)
}
import { unstable_cache } from 'next/cache'
export type Product = { export type Product = {
slug: string slug: string
name: string name: string
...@@ -17,10 +19,14 @@ const products: Product[] = [ ...@@ -17,10 +19,14 @@ const products: Product[] = [
}, },
] ]
export async function getProducts() { export const getProducts = unstable_cache(
await new Promise((resolve) => setTimeout(resolve, 100)) async () => {
return products await new Promise((resolve) => setTimeout(resolve, 100))
} return products
},
['products'],
{ revalidate: 86400 }
)
export async function getProduct(slug: string) { export async function getProduct(slug: string) {
await new Promise((resolve) => setTimeout(resolve, 100)) await new Promise((resolve) => setTimeout(resolve, 100))
......
...@@ -25,7 +25,7 @@ Enable Cache Components on an app and walk it to a passing build. This skill seq ...@@ -25,7 +25,7 @@ Enable Cache Components on an app and walk it to a passing build. This skill seq
- `npx @next/codemod@latest upgrade latest` to apply the version-to-version codemods. - `npx @next/codemod@latest upgrade latest` to apply the version-to-version codemods.
- Read the relevant [version upgrade guide](https://nextjs.org/docs/app/guides/upgrading) (e.g. [Version 16](https://nextjs.org/docs/app/guides/upgrading/version-16)) for what the codemod doesn't cover. - Read the relevant [version upgrade guide](https://nextjs.org/docs/app/guides/upgrading) (e.g. [Version 16](https://nextjs.org/docs/app/guides/upgrading/version-16)) for what the codemod doesn't cover.
- **No incompatible config keys.** `cacheComponents: true` errors on any file that still exports `dynamic`, `revalidate`, or `fetchCache`. **Translate, don't delete.** Each export encodes behavior the route needs to keep doing; migrate each one to its Cache Components equivalent via the [migration guide's per-key sections](https://nextjs.org/docs/app/guides/migrating-to-cache-components#enable-cache-components). The exception is `dynamic = 'force-dynamic'`: under Cache Components every route is already dynamic by default, so the migration guide removes it outright rather than translating it — don't overthink a batch of identical `force-dynamic` deletions. `revalidate` and `fetchCache` still need real translation. If a value can't be cleanly translated yet, leave a `// TODO: Cache Components adoption — restore revalidate = 3600` comment so the loop picks it up. The `cache-components-instant-false` codemod does not touch these. - **No incompatible config keys.** `cacheComponents: true` errors on any file that still exports `dynamic`, `revalidate`, or `fetchCache`. Inventory these exports before running the codemod, then follow the [migration guide's per-key sections](https://nextjs.org/docs/app/guides/migrating-to-cache-components). The guide is the source of truth for translating each value. The `cache-components-instant-false` codemod does not remove these configs.
- **`experimental.dynamicIO` is fatal.** It was renamed to top-level `cacheComponents` and the old key now aborts before any build can run — remove it (or replace with `cacheComponents: true`) first. `experimental.useCache` is still accepted as a deprecated alias; redundant once `cacheComponents: true` is set, so remove it for clarity. - **`experimental.dynamicIO` is fatal.** It was renamed to top-level `cacheComponents` and the old key now aborts before any build can run — remove it (or replace with `cacheComponents: true`) first. `experimental.useCache` is still accepted as a deprecated alias; redundant once `cacheComponents: true` is set, so remove it for clarity.
...@@ -33,6 +33,8 @@ Enable Cache Components on an app and walk it to a passing build. This skill seq ...@@ -33,6 +33,8 @@ Enable Cache Components on an app and walk it to a passing build. This skill seq
- **No passing baseline before the flag.** If the app already uses `"use cache"`, the pre-flag build errors with `please enable the feature flag cacheComponents`. Enabling the flag is the first thing you do (in Incremental, before the codemod; in Direct, before fixing routes) — not a thing to do _after_ getting a passing build. Note this in your starting summary so it doesn't read as a regression. - **No passing baseline before the flag.** If the app already uses `"use cache"`, the pre-flag build errors with `please enable the feature flag cacheComponents`. Enabling the flag is the first thing you do (in Incremental, before the codemod; in Direct, before fixing routes) — not a thing to do _after_ getting a passing build. Note this in your starting summary so it doesn't read as a regression.
- **Existing caches can stay.** Follow the migration guide's [`fetch` and `unstable_cache` sections](https://nextjs.org/docs/app/guides/migrating-to-cache-components#fetch-cache-options). Do not rewrite them solely to enable Cache Components.
- **Offline docs.** Guide links have offline copies under `node_modules/next/dist/docs/` (bundled since Next.js 16.2), with the directory layout numbered for ordering (e.g. `node_modules/next/dist/docs/01-app/02-guides/migrating-to-cache-components.md`). If you can't predict the numbered prefix, `find node_modules/next/dist/docs -name '<slug>.md'` resolves it. The `/docs/messages/*` error pages are not bundled. - **Offline docs.** Guide links have offline copies under `node_modules/next/dist/docs/` (bundled since Next.js 16.2), with the directory layout numbered for ordering (e.g. `node_modules/next/dist/docs/01-app/02-guides/migrating-to-cache-components.md`). If you can't predict the numbered prefix, `find node_modules/next/dist/docs -name '<slug>.md'` resolves it. The `/docs/messages/*` error pages are not bundled.
- **Older versions without bundled docs.** Suggest `npx @next/codemod@latest agents-md` to the user before starting: it downloads a version-matched copy to `.next-docs/` and writes an index into `AGENTS.md` / `CLAUDE.md`. It touches files in their repo, so ask first and run it only if they want it. - **Older versions without bundled docs.** Suggest `npx @next/codemod@latest agents-md` to the user before starting: it downloads a version-matched copy to `.next-docs/` and writes an index into `AGENTS.md` / `CLAUDE.md`. It touches files in their repo, so ask first and run it only if they want it.
...@@ -43,7 +45,7 @@ There's one loop: walk the route tree top-down, one feature at a time, adopting ...@@ -43,7 +45,7 @@ There's one loop: walk the route tree top-down, one feature at a time, adopting
The choice in step 1 is whether to opt every route out of validation first or fix routes as you go. Either way the loop is the same: The choice in step 1 is whether to opt every route out of validation first or fix routes as you go. Either way the loop is the same:
- **With a quiet pre-step (Incremental).** Run the codemod to opt every page and layout out of validation. Once you've also fixed what the codemod can't (sync-IO calls, leftover `revalidate`/`dynamic`/`fetchCache` exports), the build passes; you ship that as its own PR and then start the loop — removing one opt-out at a time and adopting that route. This splits the work into small, reviewable PRs. - **With a quiet pre-step (Incremental).** Run the codemod, fix what it can't, and fully migrate routes that previously required static rendering. Other routes keep their opt-outs for follow-up PRs.
- **Without (Direct).** Enable `cacheComponents` and start the loop on whatever the build flags first. Same loop, but every fix sits on one branch until adoption is complete. - **Without (Direct).** Enable `cacheComponents` and start the loop on whatever the build flags first. Same loop, but every fix sits on one branch until adoption is complete.
In both, the per-route success bar is the same: **dev loop reports no errors AND `next build` passes**. Check in with the user after every feature, and suggest a commit but never make one without their confirmation. Expect to spend most of the time in the loop, not in the pre-step. In both, the per-route success bar is the same: **dev loop reports no errors AND `next build` passes**. Check in with the user after every feature, and suggest a commit but never make one without their confirmation. Expect to spend most of the time in the loop, not in the pre-step.
...@@ -105,14 +107,14 @@ Ask the user, in terms of the PRs they want, not the size of the job. Never use ...@@ -105,14 +107,14 @@ Ask the user, in terms of the PRs they want, not the size of the job. Never use
If there's no user to ask, default to **Incremental** and document the choice. If there's no user to ask, default to **Incremental** and document the choice.
Honor an explicit choice in the request. If the user asks to migrate incrementally and also asks you to complete the migration, establish and verify the incremental checkpoint before continuing to the remaining routes in the same task. “Complete” sets the stopping point; it does not change the chosen strategy.
- **Incremental** — quiet pre-step + the loop. Run the codemod to opt every page and layout out of validation, get the build passing, stop and check in with the user (see [end of the pre-step](#end-of-the-pre-step-check-in)), then enter [step 2's loop](#step-2-the-inner-loop-remove-opt-outs-one-feature-at-a-time) and ship each feature as a follow-up PR. - **Incremental** — quiet pre-step + the loop. Run the codemod to opt every page and layout out of validation, get the build passing, stop and check in with the user (see [end of the pre-step](#end-of-the-pre-step-check-in)), then enter [step 2's loop](#step-2-the-inner-loop-remove-opt-outs-one-feature-at-a-time) and ship each feature as a follow-up PR.
- **Direct** — skip the pre-step. Enable `cacheComponents` and go straight to [step 2's loop](#step-2-the-inner-loop-remove-opt-outs-one-feature-at-a-time); the build's blocking routes are the work queue. - **Direct** — skip the pre-step. Enable `cacheComponents` and go straight to [step 2's loop](#step-2-the-inner-loop-remove-opt-outs-one-feature-at-a-time); the build's blocking routes are the work queue.
### incremental ### incremental
Before invoking the codemod, fix the blocker that does not require build feedback. Before invoking the codemod, grep for `^export const (revalidate|dynamic|fetchCache)` across the app directory and follow the migration guide for every match. Mark routes that use `dynamic = 'force-static'` or `dynamic = 'error'` for full migration in this PR. The codemod does not remove incompatible configs.
1. **Incompatible segment configs.** Grep for `^export const (revalidate|dynamic|fetchCache)` across the app directory and translate per the `requires` note above. The codemod does not touch them; leaving them in place fails the build after the codemod.
The codemod refuses to run on a dirty working tree. Commit or stash unrelated work first, or pass `--force` to let its edits land alongside your WIP. Common false positive: if you recently upgraded Next.js, `package.json` and the lockfile will already be dirty — commit those first. The codemod refuses to run on a dirty working tree. Commit or stash unrelated work first, or pass `--force` to let its edits land alongside your WIP. Common false positive: if you recently upgraded Next.js, `package.json` and the lockfile will already be dirty — commit those first.
...@@ -136,6 +138,8 @@ The codemod opts every segment out, not only the root, on purpose. Resolution is ...@@ -136,6 +138,8 @@ The codemod opts every segment out, not only the root, on purpose. Resolution is
Because the highest opt-out wins, remove them top-down (root layout first, then descend). Removing a leaf's opt-out does nothing while an ancestor still holds one. Because the highest opt-out wins, remove them top-down (root layout first, then descend). Removing a leaf's opt-out does nothing while an ancestor still holds one.
Remove the opt-outs from the previously static routes and any shared segments that mask their validation. Resolve their errors and confirm they still prerender. A cached data call alone does not prove the route remains static.
Next, run `next build` to surface blockers the codemod could not handle. The build is the proof, not the codemod run — a shared layout that calls `new Date()` / `Math.random()` directly still fails regardless of the opt-out (see [background](#background)). If the normal build reports a sync-IO error without locating the call, rerun that route with `next build --debug-prerender --debug-build-paths="app/path/to/page.tsx"`. For each sync-IO error it reports: Next, run `next build` to surface blockers the codemod could not handle. The build is the proof, not the codemod run — a shared layout that calls `new Date()` / `Math.random()` directly still fails regardless of the opt-out (see [background](#background)). If the normal build reports a sync-IO error without locating the call, rerun that route with `next build --debug-prerender --debug-build-paths="app/path/to/page.tsx"`. For each sync-IO error it reports:
1. **Sync-IO at module/render time.** Use the route, originating file and line, and `/docs/messages/` link in the build output to locate the error. If needed, grep the whole repo for `new Date()`, `Date.now()`, `Math.random()`, and `crypto.randomUUID()` (not only `app/**/layout.{js,jsx,ts,tsx}` — the read might live in any component imported by a layout). Do not change unreported matches. Apply the appropriate option from the linked error page, then add this comment above a temporary boundary introduced only to unblock the build: 1. **Sync-IO at module/render time.** Use the route, originating file and line, and `/docs/messages/` link in the build output to locate the error. If needed, grep the whole repo for `new Date()`, `Date.now()`, `Math.random()`, and `crypto.randomUUID()` (not only `app/**/layout.{js,jsx,ts,tsx}` — the read might live in any component imported by a layout). Do not change unreported matches. Apply the appropriate option from the linked error page, then add this comment above a temporary boundary introduced only to unblock the build:
...@@ -148,20 +152,20 @@ Next, run `next build` to surface blockers the codemod could not handle. The bui ...@@ -148,20 +152,20 @@ Next, run `next build` to surface blockers the codemod could not handle. The bui
After each fix, rerun the scoped build when available, then run `next build` again to find the next blocker. Repeat until the normal build passes. After each fix, rerun the scoped build when available, then run `next build` again to find the next blocker. Repeat until the normal build passes.
After the build passes, confirm the root layout got an opt-out (`grep -n "export const instant" <app dir>/layout.*`). The root layout renders every route, including framework routes like `/_not-found`, so if it was missed, add `export const instant = false` to it by hand. After the build passes, confirm every deferred route is still covered by an opt-out and no shared opt-out covers a previously static route. If the app has no previously static routes and the root layout remains deferred, confirm it got an opt-out (`grep -n "export const instant" <app dir>/layout.*`). The root layout renders every route, including framework routes like `/_not-found`, so if it was missed, add `export const instant = false` to it by hand.
Synthetic routes like `/_not-found` have no user file — when they block, fix the root layout's opt-out, not the synthetic route. Client Components (`"use client"`) get no opt-out (it's a build error to export `instant` from them), but they are not a rare blocker. The high-frequency case is a client component in the root layout's nav or header calling `usePathname()`/`useSearchParams()`: it blocks _every_ dynamic route with `blocking-prerender-client-hook`, and static routes pass (the pathname is known at prerender), which masks it until you reach a dynamic segment. It's not an ancestor-data fix — follow the [error's docs page](https://nextjs.org/docs/messages/blocking-prerender-client-hook) for the `<Suspense>` recipe. Only when a client route blocks on _server_ data do you fix that data in its ancestor. Synthetic routes like `/_not-found` have no user file — when they block, fix the root layout's opt-out, not the synthetic route. Client Components (`"use client"`) get no opt-out (it's a build error to export `instant` from them), but they are not a rare blocker. The high-frequency case is a client component in the root layout's nav or header calling `usePathname()`/`useSearchParams()`: it blocks _every_ dynamic route with `blocking-prerender-client-hook`, and static routes pass (the pathname is known at prerender), which masks it until you reach a dynamic segment. It's not an ancestor-data fix — follow the [error's docs page](https://nextjs.org/docs/messages/blocking-prerender-client-hook) for the `<Suspense>` recipe. Only when a client route blocks on _server_ data do you fix that data in its ancestor.
### end of the pre-step: check in ### end of the pre-step: check in
Incremental only. Stop here before starting step 2 — the pre-step is the shippable PR. Talk to the user in their language; don't say "Incremental" or other internal labels; talk about adoption, PRs, and what the app does now. Tell them: Incremental only. The pre-step is the shippable PR. Record the passing checkpoint before starting step 2. Unless the user already asked you to continue through the full migration in the same task, stop and check in. Talk to the user in their language; don't say "Incremental" or other internal labels; talk about adoption, PRs, and what the app does now. Tell them:
- What you did: turned on Cache Components, ran the codemod that opts every page and layout out of the new validation (or did it by hand), fixed any blockers the codemod can't (list them), confirmed the build passes. - What you did: turned on Cache Components, ran the codemod, migrated the previously static routes, fixed the remaining blockers, and confirmed the build passes.
- What changed: every page and layout in the app directory now exports `instant = false` with a `// TODO: Cache Components adoption` comment, except client components and any that already had an `instant` export. - What changed: the previously static routes still prerender. Other pages and layouts keep a `// TODO: Cache Components adoption` opt-out.
- What to sanity-check: the diff is mostly mechanical (new exports + comments). The build passes. Routes still behave exactly as they did before — the opt-outs preserve current behavior; no rendering changes yet. - What to sanity-check: the previously static routes stay fully prerendered and prefetchable, and request-specific data on the deferred routes remains request-specific.
- The question: "Want to open this as its own PR before we start adopting Cache Components route by route? Or keep going on this branch?" Wait for the answer. - The question: "Want to open this as its own PR before we start adopting Cache Components route by route? Or keep going on this branch?" Wait for the answer.
Moving to step 2 without checking in defeats the point of taking the incremental path. If the user already asked you to complete the migration, continue after recording this checkpoint instead of asking the same question again.
### direct ### direct
......
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