Next cache components adoption

From motormetrics/motormetrics · View interactive version

Next cache components adoption is an AI agent skill from the GitHub repository motormetrics/motormetrics. Turn on Cache Components in a Next.js app and resolve the blocking routes it surfaces. Use when the user wants to enable, adopt, or migrate to Cache Components, flip the `cacheComponents` flag, work through a flood of blocking-prerender / instant validation errors, run the `cache-components-instant-

How to use this skill

Skill file

next-cache-components-adoption

Enable Cache Components on an app and walk it to a passing build. This skill sequences the work; per-error recipes live in the dev overlay fix cards and the build's terminal output. The migrating to Cache Components guide is the canonical reference for the concepts and per-API recipes this skill applies — consult it whenever the skill steps reference a pattern ("use cache", cacheLife, <Suspense> placement, etc.) and you want the full explanation.

requires

notes

the shape of the work

There's one loop: walk the route tree top-down, one feature at a time, adopting each route against next dev + a browser. The build is a final check for each feature, not the working surface.

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:

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.

background

cacheComponents: true requires every route to be prerenderable. A route that reads request-time data outside <Suspense> is "blocking" and fails the build. export const instant = false marks a route as allowed to block, which clears it in both dev and build; on a layout it covers the whole subtree during the build, but client navigations still validate each descendant segment on its own. Reads wrapped in a CODE3 function count as cache boundaries, not blocking reads.

When a fix introduces "use cache", follow the Caching guide for choosing a data-level or UI-level boundary and setting its lifetime and revalidating after mutations. Use the CODE1 cache-key reference when the result varies by arguments or captured values.

Three classes of blocker come up, usually in this order:

Whenever a fix introduces <Suspense>, follow the Streaming guide's granular streaming pattern and guidance for preventing CLS.

  1. Request-time reads (cookies(), headers(), await params, await searchParams). All four block when awaited at the top of a page or layout. params and searchParams often get missed because they're not framed as "request data" the way cookies and headers are. The fix is to push the read into a <Suspense>-wrapped child — and for params/searchParams, forward the promise into the child and await it there; don't await at the page top.
  2. Sync-IO at module/render time (new Date(), Date.now(), Math.random(), crypto.randomUUID()). These fail the build even with instant = false — the opt-out doesn't suppress them. If they're in a shared layout, they block every route under it. The codemod can't fix them; after running it, use each build error and its linked documentation to identify which reported calls to translate by hand (see the incremental pre-step).
  3. "use cache" files that read request data. A file with a top-level "use cache" directive can't export instant; combining the two errors with Only async functions are allowed to be exported in a "use cache" file., which means the directive was wrong for that route. Remove it before running the codemod.

working surfaces

finding blocking routes

Prefer next dev over next build while you work.

Every blocking error has a docs page — open it. Both the dev overlay and the build terminal print a https://nextjs.org/docs/messages/<slug> link with each error. That page is the canonical recipe for the fix; the inline message is a summary. Fetch the link for every distinct error you encounter, even if you think you know the pattern — the recipes evolve, and the same error class can have different correct fixes depending on what the route reads. Don't improvise from the inline message alone. (/docs/messages/* pages aren't bundled offline; if you have no network, fall back to the per-API guides under node_modules/next/dist/docs/ and note the limitation when you report back.)

verifying each fix at runtime

A passing build or a cleared overlay isn't proof the route actually behaves — Cache Components is a runtime concern (a static shell with streamed data). Verify after every fix, not only at the end.

In preference order:

  1. CODE0 — strongly preferred. Cross-checks /_next/mcp against the live browser via agent-browser and surfaces both compile and runtime issues in one pass. The diagnostics (React tree, suspense boundaries, console + network) are richer than poking at next dev by hand.

Install it before starting the loop. Don't wait until you hit something next dev alone can't explain. It ships alongside this skill, so check whether it is already available first, and install it only if it is not:

```bash

npx skills add https://github.com/vercel/next.js/tree/canary/skills/next-dev-loop

```

The skill states its required agent-browser version and walks you through it.

Requires Turbopack. If package.json's dev script passes --webpack, flag it to the user and ask whether there's a reason to stay on webpack. If not, switch to Turbopack (the Next.js 16.3+ default). If they want to keep webpack, skip this install and use the build-only loop instead.

You don't need permission to install next-dev-loop itself. It's a tool, like installing a dev dependency. If a user is present, briefly tell them you're installing it for verification. In a non-interactive run (CI, dashboard, sandbox), install it without asking — "can't prompt the user" is not a reason to skip. The only legitimate skip is a real technical blocker: no network, no npm, read-only filesystem, a stated no-new-deps policy, or a webpack-only dev script. If you skip, name the specific blocker in your final report.

  1. A browser you can drive yourself. Playwright, agent-browser directly, any browser-automation tool. Use only when next-dev-loop is genuinely blocked. You'll miss the framework-side checks (/_next/mcp), so DOM assertions alone don't catch every regression — be more cautious about what you call "verified."
  1. Build-only. If you can't run a dev server at all, the build is your only signal. ○ (Static) routes with no <Suspense> are fully verified by the build (nothing streamed to test). ◐ (Partial Prerender) routes are only shell-verified — flag them when you report back.
  1. No tooling at all. Ask the user to run the dev server (or build) and report what they see, or hand off the milestone you've reached.

step 1: choose a strategy

Ask the user, in terms of the PRs they want, not the size of the job. Never use the internal labels (Incremental, Direct) when talking to the user — those are your own scaffolding. Ask in terms of PRs and features, e.g.: _"Do you want me to first open a PR that turns on Cache Components and opts every route out of validation, then handle the actual route adoptions feature-by-feature in follow-up PRs? Or do everything on one branch?"_ Even on a tiny app, the incremental path still has value (review-sized PR, revertible, the // TODO: Cache Components adoption markers double as your work queue for next session). Don't pick on their behalf.

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

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.

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.

npx @next/codemod@latest cache-components-instant-false ./app

Pass the app directory you resolved in requires. A wrong path is not an error: it reports 0 ok and exits 0, so read the file count and treat zero as a failed run, not an adopted app.

Inserts export const instant = false (with a // TODO: Cache Components adoption comment) into every {page,layout,default} file under that directory, skipping files that already declare instant and any module marked "use client" or "use server". Then set cacheComponents: true. The TODO comments are the work queue for the loop.

If the codemod isn't available (older @next/codemod, sandboxed environment, offline run), reproduce it by hand: for every {page,layout,default}.{js,jsx,ts,tsx} in the app directory that isn't "use client" or "use server" and doesn't already declare instant, insert this after the imports:

// 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

The codemod opts every segment out, not only the root, on purpose. Resolution is top-down, first-explicit-config-wins: the highest instant = false decides the whole subtree. With an opt-out on every segment, removing one segment's opt-out validates only that segment; descendants keep their own opt-outs and stay passing. If only the root were opted out, removing it would re-arm validation for the entire app at once.

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). 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:

```tsx

// TODO: Cache Components adoption. Added to unblock the build: remove this boundary to re-trigger the error and review the documented options.

```

It shares the TODO: Cache Components adoption prefix with the comments the codemod writes, so the check-in grep finds both. Removing the boundary makes the error fire again with its fix cards — the same motion as removing an opt-out in the loop.

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 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 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

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:

If the user already asked you to complete the migration, continue after recording this checkpoint instead of asking the same question again.

direct

Set cacheComponents: true and move to step 2. The build's blocking routes are the work queue.

step 2: the inner loop, remove opt-outs one feature at a time

A "feature" is a single product surface — app/settings/profile/**, app/posts/[slug]/** — not a whole top-level app like app/dashboard/**. Finish one end-to-end before starting the next.

Within a feature, walk top-down (layouts before pages, root layout first). Removing a layout's opt-out before its descendants exposes the layout's own blocking reads. (Direct: there are no opt-outs to remove — fix each failing route; if a hand-written opt-out on an ancestor shadows it, remove that first.)

A passing build mid-walk doesn't mean the layout is clean. Removing a layout's opt-out while its descendant pages still have theirs keeps the build passing — each page shadows the inherited validation. The layout's actual blocking reads only surface once nothing below it shadows them. Don't call a feature done at the layout boundary.

Use the with-a-browser loop unless a browser is genuinely unreachable. The CODE0 skill is the source of truth for what counts as "browser available" and how to install it.

the loop, with a browser (preferred)

Per route:

the loop, build-only (fallback)

Used when there's no way to drive a browser — CI, sandbox, the user has no next dev running and you can't start one. Weaker signal: confirms the build passes and the route prerenders, but not what ended up in the static shell vs streamed.

Per route:

loop notes

Keep a todo list of the feature's routes. When every route in the feature is clean, move to step 3.

step 3: verify the feature

Checklist before checking in with the user:

Then check in with the user. Same rule as the pre-step: speak their language. Don't say "feature-by-feature loop" or other internal labels; talk about the feature you adopted and what the user will see.

Trivial features can skip the check-in. If adopting a feature only meant removing its // TODO: Cache Components adoption opt-out (no <Suspense> added, no 'use cache' introduced, no render order change), the user sees nothing different. Move on to the next feature without stopping; mention it in passing the next time you do check in.

When the loop has run on every feature — every remaining instant = false sits under a reason comment, grep -rln "TODO: Cache Components adoption" app returns nothing — point the user at further reading if they want to push the experience further, or stop and ship.

route table glyphs

ƒ → ◐ is where adoption usually lands. ◐ (Partial Prerender) means a static shell prerenders and the request-time content streams in — the goal state for any route that reads cookies(), headers(), params, or searchParams. Some routes legitimately stay ƒ when they do request-time work through a documented escape hatch (e.g. a layout that uses await connection()); the page is no longer _opted out_, it's genuinely dynamic. Don't remove the escape hatch only to chase a ◐. The inverse holds: instant = false does not force a route to be ƒ. The glyph reflects what the route does at prerender time, not which validation knobs it exports.

◐ tells you a shell exists, not what's in it. A <Suspense> boundary placed too high (e.g. wrapping the entire page body, or <Suspense fallback={null}> around the article content) pushes the visible content out of the static shell into the streamed payload; the build still reports ◐ because _some_ shell prerendered (often only <html><body> with framework markup). The route table can't tell you what's in the shell; a browser can. If the shell is empty and everything streams, pull the <Suspense> boundary down closer to the actual dynamic read.

further reading

The work below is optional and lives in the docs — link the user to them and let them decide which to take on next. Don't walk these through inside this skill.

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.