Unverified Commit ae62a6f7 authored by Aurora Scharff's avatar Aurora Scharff Committed by GitHub

codemod: cache-components-instant-false + next-cache-components-adoption skill (#94941)

### Why?

Turning on `cacheComponents` makes every blocking route a build error at
once. On a large app that's a wall of failures with no clear order to
fix them in, which is a rough first experience.

### What?

An opt-in adoption path so enabling Cache Components doesn't have to be
all-or-nothing:

- **`cache-components-instant-false` codemod** (`@next/codemod`) —
blanket-inserts `export const instant = false` (with a `// TODO: Cache
Components adoption` comment) into every `app/**/{page,layout}` file, so
the build goes green immediately. Idempotent: skips files that already
export `instant` (including aliased `export { x as instant }`). Skips
Client Components (`"use client"`) and route handlers.
- **`next-cache-components-adoption` skill** (`skills/`) — sequences the
full migration in five steps across four milestones: green build
(codemod or direct), remove the opt-outs top-down one group at a time,
make navigations instant via the dev-overlay Insights, then adopt
Partial Prefetching. It defers individual fixes to the dev overlay fix
cards, stack traces, and the `/docs/messages/blocking-prerender-*`
pages, and points at the migration / instant-navigation / Partial
Prefetching guides rather than re-teaching them. Verifies each change at
runtime via `next-dev-loop` (with a manual dev-overlay fallback). The
`next-cache-components-optimizer` skill is referenced only as optional
shell-growing polish after adoption is complete.

### How?

- Transform registered in `TRANSFORMER_INQUIRER_CHOICES` at `version:
'16.3.0'`.
- 8 fixtures cover insert-into-page / -layout, JSDoc placement, and
no-op on existing / aliased / multi-declarator / local-binding `instant`
and on `"use client"` pages. `pnpm jest cache-components-instant-false`
passes.
- Docs: a `cache-components-instant-false` entry in the codemods
reference, and a pointer to the skill + codemod from the migration
guide.
parent f0d1956c
...@@ -20,6 +20,12 @@ The migration is driven by **instant navigation validation**. With Cache Compone ...@@ -20,6 +20,12 @@ The migration is driven by **instant navigation validation**. With Cache Compone
Start by removing the route segment configs (`dynamic`, `revalidate`, `fetchCache`), then follow the validation insights and errors. Each one names the code to fix, most often uncached data to cache with [`use cache`](/docs/app/api-reference/directives/use-cache) or runtime data to wrap in [`<Suspense>`](https://react.dev/reference/react/Suspense). If a route needs more work than you want to take on right now, you can [opt it out of validation](#opting-out-of-validation) and come back to it later. Start by removing the route segment configs (`dynamic`, `revalidate`, `fetchCache`), then follow the validation insights and errors. Each one names the code to fix, most often uncached data to cache with [`use cache`](/docs/app/api-reference/directives/use-cache) or runtime data to wrap in [`<Suspense>`](https://react.dev/reference/react/Suspense). If a route needs more work than you want to take on right now, you can [opt it out of validation](#opting-out-of-validation) and come back to it later.
> **Good to know:** For agents working on larger apps, the [`next-cache-components-adoption`](https://github.com/vercel/next.js/tree/canary/skills/next-cache-components-adoption) skill drives this guide route by route. It can blanket-opt-out the app with `instant = false` to unblock the build, work each opt-out back off, help decide what becomes instant and what stays blocking, and walk the dev-overlay validation insights with you. Install with:
>
> ```bash filename="Terminal"
> npx skills add https://github.com/vercel/next.js/tree/canary/skills/next-cache-components-adoption
> ```
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 as a separate layer, so let the insights and errors guide what to change.
Some surfaces have their own steps: Some surfaces have their own steps:
......
...@@ -61,6 +61,30 @@ npx @next/codemod upgrade canary ...@@ -61,6 +61,30 @@ npx @next/codemod upgrade canary
## Codemods ## Codemods
### 16.3
#### Opt every route out of Cache Components validation
##### `cache-components-instant-false`
```bash filename="Terminal"
npx @next/codemod@canary cache-components-instant-false ./app
```
This codemod adds `export const instant = false` to every `app/**/{page,layout,default}` file that doesn't already export `instant`, so you can enable [`cacheComponents`](/docs/app/api-reference/config/next-config-js/cacheComponents) and then remove the opt-outs route by route. It skips Client Components (`"use client"`) and files that already declare `instant`.
```diff filename="app/page.tsx"
+ // TODO: Cache Components adoption. Refactor this route so this opt-out can be removed.
+ // See: https://nextjs.org/docs/app/guides/migrating-to-cache-components
+ export const instant = false
+
export default function Page() {
return <h1>Hello</h1>
}
```
See the [Migrating to Cache Components](/docs/app/guides/migrating-to-cache-components) guide for the full adoption path.
### 16.0 ### 16.0
#### Remove `experimental_ppr` Route Segment Config from App Router pages and layouts #### Remove `experimental_ppr` Route Segment Config from App Router pages and layouts
......
...@@ -143,4 +143,10 @@ export const TRANSFORMER_INQUIRER_CHOICES = [ ...@@ -143,4 +143,10 @@ export const TRANSFORMER_INQUIRER_CHOICES = [
value: 'remove-experimental-ppr', value: 'remove-experimental-ppr',
version: '16.0.0-canary.11', version: '16.0.0-canary.11',
}, },
{
title:
'Add `export const instant = false` to App Router pages and layouts to ease Cache Components adoption',
value: 'cache-components-instant-false',
version: '16.3.0',
},
] ]
// @ts-nocheck
const config = false;
export { config as instant };
export default function Page() {
return <p>aliased export</p>;
}
// @ts-nocheck
const config = false;
export { config as instant };
export default function Page() {
return <p>aliased export</p>;
}
// @ts-nocheck
export const instant = true;
export default function Page() {
return <p>already opted in</p>;
}
// @ts-nocheck
export const instant = true;
export default function Page() {
return <p>already opted in</p>;
}
// @ts-nocheck
export default function Default() {
return <p>parallel route fallback</p>;
}
// @ts-nocheck
// TODO: Cache Components adoption. Refactor this route so this opt-out can be removed.
// See: https://nextjs.org/docs/app/guides/migrating-to-cache-components
export const instant = false;
export default function Default() {
return <p>parallel route fallback</p>;
}
// @ts-nocheck
export default function Layout({ children }) {
return <section>{children}</section>;
}
// @ts-nocheck
// TODO: Cache Components adoption. Refactor this route so this opt-out can be removed.
// See: https://nextjs.org/docs/app/guides/migrating-to-cache-components
export const instant = false;
export default function Layout({ children }) {
return <section>{children}</section>;
}
// @ts-nocheck
export default function Page() {
return <p>hello world</p>;
}
// @ts-nocheck
// TODO: Cache Components adoption. Refactor this route so this opt-out can be removed.
// See: https://nextjs.org/docs/app/guides/migrating-to-cache-components
export const instant = false;
export default function Page() {
return <p>hello world</p>;
}
// @ts-nocheck
const config = { instant: false }
const { instant } = config
export default function Page() {
return <p>destructured binding</p>
}
export { instant }
// @ts-nocheck
const config = { instant: false }
const { instant } = config
export default function Page() {
return <p>destructured binding</p>
}
export { instant }
// @ts-nocheck
/**
* A page with a leading JSDoc banner.
* The opt-out must be appended after this block, not inside it.
*/
export default function Page() {
return <p>jsdoc page</p>;
}
// @ts-nocheck
/**
* A page with a leading JSDoc banner.
* The opt-out must be appended after this block, not inside it.
*/
// TODO: Cache Components adoption. Refactor this route so this opt-out can be removed.
// See: https://nextjs.org/docs/app/guides/migrating-to-cache-components
export const instant = false;
export default function Page() {
return <p>jsdoc page</p>;
}
// @ts-nocheck
const instant = false;
export default function Page() {
return <p>local binding</p>;
}
export { instant };
// @ts-nocheck
const instant = false;
export default function Page() {
return <p>local binding</p>;
}
export { instant };
// @ts-nocheck
export const dynamic = 'force-dynamic',
instant = true;
export default function Page() {
return <p>multi-declarator export</p>;
}
// @ts-nocheck
export const dynamic = 'force-dynamic',
instant = true;
export default function Page() {
return <p>multi-declarator export</p>;
}
// @ts-nocheck
import {
Suspense,
type ReactNode,
} from 'react'
import {
foo,
bar,
} from './lib'
export default function Page({ children }: { children: ReactNode }) {
return <Suspense>{foo(bar()) || children}</Suspense>
}
// @ts-nocheck
import {
Suspense,
type ReactNode,
} from 'react'
import {
foo,
bar,
} from './lib'
// TODO: Cache Components adoption. Refactor this route so this opt-out can be removed.
// See: https://nextjs.org/docs/app/guides/migrating-to-cache-components
export const instant = false;
export default function Page({ children }: { children: ReactNode }) {
return <Suspense>{foo(bar()) || children}</Suspense>
}
// @ts-nocheck
'use client'
export default function Page() {
return <p>client page</p>;
}
// @ts-nocheck
'use client'
export default function Page() {
return <p>client page</p>;
}
// @ts-nocheck
import { Suspense } from 'react'
import { foo } from './bar'
interface Props {
id: string
}
export default function Page({ id }: Props) {
return <Suspense>{foo(id)}</Suspense>
}
// @ts-nocheck
import { Suspense } from 'react'
import { foo } from './bar'
// TODO: Cache Components adoption. Refactor this route so this opt-out can be removed.
// See: https://nextjs.org/docs/app/guides/migrating-to-cache-components
export const instant = false;
interface Props {
id: string
}
export default function Page({ id }: Props) {
return <Suspense>{foo(id)}</Suspense>
}
/* global jest */
jest.autoMockOff()
const defineTest = require('jscodeshift/dist/testUtils').defineTest
const { readdirSync } = require('fs')
const { join } = require('path')
const fixtureDir = 'cache-components-instant-false'
const fixtureDirPath = join(__dirname, '..', '__testfixtures__', fixtureDir)
const fixtures = readdirSync(fixtureDirPath)
.filter((file) => file.endsWith('.input.tsx'))
.map((file) => file.replace('.input.tsx', ''))
for (const fixture of fixtures) {
const prefix = `${fixtureDir}/${fixture}`
defineTest(__dirname, fixtureDir, null, prefix, { parser: 'tsx' })
}
import type { API, FileInfo } from 'jscodeshift'
import { createParserFromPath } from '../lib/parser'
/**
* Blanket-inserts `export const instant = false` into every App Router `page`,
* `layout`, and `default` file so they're marked as allowed to block when
* `cacheComponents` is enabled. Each opt-out is meant to be walked back, one
* route at a time, using the companion adoption skill.
*
* - Skips files that already declare or export `instant` in any form (never
* overrides existing config or appends a duplicate binding).
* - Skips Client/Server Component modules (`"use client"` / `"use server"`):
* `instant` is a Server Component route segment config, so exporting it from
* those modules is a build error.
* - Targets `page` / `layout` / `default` only (not `route` — `instant` does
* not apply to route handlers). `default.tsx` is the parallel-route fallback,
* a server segment that accepts route segment config like the other two.
*/
export default function transformer(file: FileInfo, _api: API) {
if (
process.env.NODE_ENV !== 'test' &&
!/(^|[/\\])app[/\\].*?(page|layout|default)\.[^/\\]+$/.test(file.path)
) {
return file.source
}
const j = createParserFromPath(file.path)
const root = j(file.source)
// Bail on Client/Server Component modules. `instant` is a Server Component
// route segment config; exporting it from a `"use client"` (or `"use server"`)
// module fails the build. Parsers represent the directive either in
// `program.directives` or as a leading string-literal `ExpressionStatement`.
const program = root.get().node.program
const isClientOrServerDirective = (value: unknown) =>
value === 'use client' || value === 'use server'
let hasModuleDirective = (program.directives ?? []).some((d: any) =>
isClientOrServerDirective(d?.value?.value)
)
if (!hasModuleDirective) {
for (const node of program.body) {
if (
node.type !== 'ExpressionStatement' ||
(node.expression?.type !== 'StringLiteral' &&
node.expression?.type !== 'Literal')
) {
// Directives must lead the module; stop at the first non-directive.
break
}
if (isClientOrServerDirective(node.expression.value)) {
hasModuleDirective = true
break
}
}
}
if (hasModuleDirective) {
return file.source
}
// Bail if `instant` already exists in any form, so we never append a
// duplicate declaration (which would be a `SyntaxError`). This covers:
// export const instant = ...
// export const a = 1, instant = ... (any declarator position)
// const instant = ... (local binding)
// const { instant } = ... (destructured binding)
// export { instant }
// export { foo as instant }
// export function instant() {} / export class instant {}
const bindsInstant = (node: any): boolean => {
switch (node?.type) {
case 'Identifier':
return node.name === 'instant'
case 'ObjectPattern':
return node.properties.some((prop: any) =>
prop.type === 'RestElement'
? bindsInstant(prop.argument)
: bindsInstant(prop.value ?? prop.argument)
)
case 'ArrayPattern':
return node.elements.some((el: any) => el != null && bindsInstant(el))
case 'AssignmentPattern':
return bindsInstant(node.left)
case 'RestElement':
return bindsInstant(node.argument)
default:
return false
}
}
const hasInstantBinding =
root
.find(j.VariableDeclarator)
.filter((p) => bindsInstant(p.node.id))
.size() > 0 ||
root.find(j.ExportSpecifier, { exported: { name: 'instant' } }).size() >
0 ||
root.find(j.FunctionDeclaration, { id: { name: 'instant' } }).size() > 0 ||
root.find(j.ClassDeclaration, { id: { name: 'instant' } }).size() > 0
if (hasInstantBinding) {
return file.source
}
// Build `export const instant = false`. The two `//` comments above it
// (TODO + See:) are attached as leading comments on the declaration so
// recast prints them right above it.
const todoComment = j.commentLine(
' TODO: Cache Components adoption. Refactor this route so this opt-out can be removed.',
true,
false
)
const seeComment = j.commentLine(
' See: https://nextjs.org/docs/app/guides/migrating-to-cache-components',
true,
false
)
const instantExport = j.exportNamedDeclaration(
j.variableDeclaration('const', [
j.variableDeclarator(j.identifier('instant'), j.booleanLiteral(false)),
])
)
instantExport.comments = [todoComment, seeComment]
// Insert after the last top-level import, or at the top of the module
// if there are no imports.
const body = program.body as any[]
let lastImportIndex = -1
for (let i = 0; i < body.length; i++) {
if (body[i].type === 'ImportDeclaration') lastImportIndex = i
}
if (lastImportIndex !== -1) {
body.splice(lastImportIndex + 1, 0, instantExport)
} else if (body.length > 0) {
// No imports. Inserting at index 0 would steal any file-level leading
// comments (e.g. `// @ts-nocheck`) from `body[0]` because recast
// attributes them to whatever is first. Move those leading comments
// off `body[0]` onto the new export *before* its TODO/See: lines, so
// they print in their original position.
const first = body[0]
const allComments = (first.comments ?? []) as any[]
const firstLeading = allComments.filter((c) => c.leading === true)
if (firstLeading.length > 0) {
first.comments = allComments.filter((c) => c.leading !== true)
instantExport.comments = [...firstLeading, todoComment, seeComment]
}
body.unshift(instantExport)
} else {
body.push(instantExport)
}
return root.toSource()
}
This diff is collapsed.
# per-page decisions: removing `instant = false`
Read this when a route still blocks after you remove its `instant = false` and the dev overlay's fix card isn't enough on its own. Each section here covers a judgment call the agent shouldn't make alone.
## deciding what to do with a blocking read
Read the full linked page behind the fix card — not only the inline snippet — before editing. The card unblocks the build, but the page covers the details that make the route's navigation actually instant (e.g. where to place a `<Suspense>` boundary). Don't improvise.
If you're unsure which fix fits, the right call usually depends on what this part of the page is _for_, which the code doesn't capture. Ask the user about their goal for it rather than guessing. Frame it as a product/UX question: should this content be there instantly on load, or is it fine for it to stream in a moment later? Should everyone see the same thing (cacheable) or is it per-user / per-request? Tie the technical fix to that answer (cache it, wrap it in `<Suspense>`, or keep it request-time), so they're deciding the experience, not the API.
## security gates and other code you can't infer
If the blocking code looks like it's there for a _reason you can't infer_ — a security gate at the page top (`await verifyAccess()`, an auth redirect, a feature-flag check) where moving it inside `<Suspense>` would change what the code guarantees — stop and ask the user before refactoring. The build error wants `<Suspense>`, but wrapping a gate in `<Suspense>` defeats the gate. Only the person who wrote it knows whether to keep the route blocking (`instant = false` as a documented Block), restructure the page so the gate runs differently, or move the check to [Proxy](https://nextjs.org/docs/app/api-reference/file-conventions/proxy).
If _every_ route under a layout is gated this way, a documented Block on the layout is the correct end state. Moving the gate to [Proxy](https://nextjs.org/docs/app/api-reference/file-conventions/proxy) is the architectural fix, not a Cache Components one, and that's a follow-up rather than something to hold the migration on.
For the broader picture, read the [Authentication guide](https://nextjs.org/docs/app/guides/authentication) (where auth checks belong: Proxy for routing, Data Access Layer for data) and the [Data Access Layer section of Data Security](https://nextjs.org/docs/app/guides/data-security#data-access-layer) (centralized auth checks that compose with `'use cache'`).
If you don't know how to make a piece of code Cache Components–correct without changing what it does, ask.
## when to leave a Block in place
If a route is genuinely meant to block — it's inherently per-request with no useful static shell — or the refactor would be large and the user would rather not take it on now, that's a legitimate outcome. Keep `instant = false`, but confirm it with the user first and turn its `// TODO: Cache Components adoption` comment into a reason, e.g. `// instant = false: kept on purpose — fully request-time dashboard` or `// instant = false: deferred, refactor too large for now`.
A documented, deliberate Block is fine to leave after the migration; an undocumented leftover opt-out is not.
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