1. Instant Static Shell + Streamed Request Holes
Traditional SSR makes the user wait for the slowest database query before painting a single pixel. Turning on cacheComponents: true flips that default: every App Router route prerenders an immediate App Shell and streams request-specific holes into <Suspense>.
Quick Navigation
next-dev-loopPart 6
2. Prerequisites & Adoption Strategy MatrixPart 2
8. Partial Prefetching & URL-Data SweepsPart 7
3. Annotated next dev + /_next/mcp TourPart 3
9. 5 Real-World Copy-Paste RecipesPart 8
4. Resolving the 3 Blocker ClassesPart 4
10. Regression Proof with instant()Part 9
5. Mastering "use cache" & Boundary AnatomyPart 5
11. Cross-Tool Vercel Synergy PipelinePart 10
6. Troubleshooting Clinic & Pre-FlightPart 11
How cacheComponents: true Splits Every Route
Since Next.js 16.2, full App Router guides live directly inside node_modules/next/dist/docs/ (e.g., 01-app/02-guides/migrating-to-cache-components.md). Use find node_modules/next/dist/docs -name '*.md' to read exact API recipes offline.
AGENTS.md IndexWorking on an older tree or want coding agents grounded in exact Next.js 16.3+ rules? Run npx @next/codemod@latest agents-md to populate .next-docs/ and write a compact framework index straight into your repository’s AGENTS.md.
<Suspense> wrapper around your entire page passes build validation but ships a blank spinner. Great Cache Components apps put headers, navigation, and shared catalog cards inside the instant shell, leaving only personalized or live request holes behind tight <Suspense> boundaries.
2. Prerequisites, Flag Migration & Strategy Matrix
Before flipping cacheComponents: true, verify that your project runs Next.js 16.3+ App Router and strip out legacy route-segment flags that conflict with fine-grained prerendering.
# Upgrade Next.js, React, and codemods together
npx @next/codemod@latest upgrade latest
npx next --version # Must be 16.3.0 or newerCache Components applies to app/ (or src/app/). If both folders exist, Next.js builds app/ and silently ignores src/app/. Hybrid pages/ routes continue working untouched.
experimental.dynamicIOis fatal: Renamed to top-levelcacheComponents; leaving the old key aborts startup before any build runs.- Remove
experimental.useCache: Deprecated alias oncecacheComponents: trueis enabled. - Inventory route exports:
cacheComponents: trueerrors on any file still exportingdynamic,revalidate, orfetchCache—migrate those manually first (existingfetch&unstable_cachecalls can stay).
// next.config.ts — clean Next.js 16.3+ baseline (delete experimental.dynamicIO first!)
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
cacheComponents: true,
}
export default nextConfigDecision Matrix: Incremental Adoption vs. Direct Adoption
| Dimension | Incremental Adoption (Recommended for Teams) | Direct Adoption (Small Apps / Single Branch) |
|---|---|---|
| Pre-Step Action | Run npx @next/codemod@latest cache-components-instant-false ./app (or ./src/app) on a clean Git working tree, then enable cacheComponents: true. |
Skip the codemod, set cacheComponents: true immediately, and use next build / next dev errors as your single-branch queue. |
| What Gets Modified | Codemod inserts // TODO: Cache Components adoption + export const instant = false into every Server page, layout, and default file. |
No temporary opt-out markers added; every blocking route fails validation immediately until refactored in place. |
| PR & Review Shape | Ship a green baseline PR immediately (migrating previously force-static routes), then remove opt-outs feature-by-feature across small PRs. |
All fixes sit together on one branch until every route in the app passes validation. |
| Hidden Gotchas | Codemod refuses dirty Git trees (use --force or commit lockfiles first) and cannot bypass Sync-IO calls (new Date(), Math.random()). |
Large apps surface dozens of cascading layout errors at once; harder to bisect regressions during review. |
export const instant = false Resolves: Top-Down Build Shield vs. Client Navsexport const instant = false to every segment intentionally. During next build, the highest ancestor instant = false shields its entire subtree; during client-side navigations, Next.js still validates each descendant segment individually. Removing opt-outs top-down keeps every child safely deferred until you reach it.
3. Annotated Tour: next dev Overlay & /_next/mcp
Do not rely on HTTP 200 status codes or guesswork while migrating. Next.js 16.3+ pairs the browser dev overlay, amber Insights cards, and the live /_next/mcp server so you see every blocking read and React boundary in real time.
/projects/[slug] awaited cookies() in app/projects/[slug]/page.tsx:14.Docs: https://nextjs.org/docs/messages/blocking-prerender-runtime
params awaited before leaf <Suspense>; shared App Shell ties to one URL.Docs: https://nextjs.org/docs/messages/instant-shell-url-data
nextjs-portal shadow DOM; /_next/mcp exposes errors cleanly over HTTP.
get_compilation_issues • get_logs
Interface Legend: The 7 Live Diagnostics Touchpoints
next dev with the exact offending line and canonical https://nextjs.org/docs/messages/... recipe link.
/_next/mcp Turbopack Endpoint: Built-in MCP server reporting routes, active segment files, compilation status, and server errors in one structured call.
instant-shell-url-data); disappears completely once every visited route is clean.
<Suspense> Tree View: Confirms via React DevTools that static chrome commits on frame 1 while only genuine dynamic leaves suspend.
--debug-prerender Trace: Disables early-exit on next build and prints full originating file-and-line traces across all blocking routes at once.
get_errors & get_page_metadata: Remember that prefetch insights surface in get_errors and dev logs—not the experimental get_request_insights recorder.
@next/playwright instant() Lock Verdict: Runs against a production next build && next start server to prove mathematically that the static shell renders immediately while deferred data is locked out.
4. Resolving the 3 Blocker Classes
Almost every prerender error during Cache Components adoption belongs to one of three predictable families. Fix the exact offending boundary rather than wrapping whole pages in a giant fallback.
Culprits: cookies(), headers(), await params, await searchParams at page or layout top.
Fix: Move the read into a focused child component inside <Suspense>. Never await params at page top—forward the params or searchParams promise straight into the child and await it there.
Culprits: new Date(), Date.now(), Math.random(), crypto.randomUUID() during render.
Fix: These fail next build even with instant = false! If inside a shared layout, they break every child route. Run --debug-prerender, move into a "use cache" helper, or isolate behind <Suspense> / connection().
Culprit: blocking-prerender-client-hook from usePathname() or useSearchParams() in root nav.
Trap: Static pages pass (pathname is known at build) and hide the bug until you hit a dynamic route! Wrap the hook-reading client leaf in <Suspense> while keeping the outer nav bar static.
// WRONG: top-level await blocks the entire route shell
export default async function PostPage({
params,
}: { params: Promise<{ slug: string }> }) {
const { slug } = await params // Blocks before Suspense!
return <Article slug={slug} />
}// RIGHT: forward the promise into a Suspense child
export default function PostPage({
params,
}: { params: Promise<{ slug: string }> }) {
return (
<ShellLayout>
<Suspense fallback={<ArticleSkeleton />}>
<ArticleBody params={params} />
</Suspense>
</ShellLayout>
)
}
cookies(), headers(), forwarded params, and usePathname() leaves) stream cleanly into recessed <Suspense> bays.
5. Mastering "use cache", cacheLife & Keys
When data is shared across visitors or changes on a predictable schedule, promote it into your static shell with "use cache" instead of streaming it on every request.
Data-Level vs. UI-Level Cache + Revalidation
import { cacheLife, cacheTag, updateTag } from 'next/cache'
export async function CatalogGrid({ category }: { category: string }) {
'use cache'
cacheLife('hours') // Built-in or custom profile
cacheTag('catalog', 'cat-' + category)
const items = await db.products.findMany({ where: { category } })
return <ProductCards items={items} />
}
// Inside a Server Action after mutation:
export async function publishProduct(category: string) {
'use server'
await db.products.create(...)
updateTag('cat-' + category) // Immediate read-your-own-writes
}Cache Key Rules & Request-Data Guardrails
cookies() Inside "use cache": Read session or locale outside in a <Suspense> parent, then pass serializable primitives (e.g., orgId) in as arguments.<Suspense fallback> dimensions (fixed heights, aspect boxes) to resolved content so streamed inserts never jump the page.Anatomy of a Clean Cache + Suspense Boundary Refactor
next build Does Not Prove "use cache" Is Safecookies(), headers(), or auth session helper called deep inside a "use cache" call tree often passes next build silently, then throws a runtime error when a real user hits next start. Always verify every newly cached subtree against a live production run (next build && next start) and test its mutation invalidation path.
6. Top-Down Loop & next-dev-loop Verification
Adopt one product feature at a time (e.g., app/settings/profile/**), walking strictly top-down from root layout to leaf pages while cross-checking /_next/mcp against a real browser.
Validation follows first-explicit-config-wins top-down resolution:
- Ancestor shields children: Removing
export const instant = falseon a leaf does nothing while its parent layout still exportsinstant = false. - Children shield ancestor: Removing a layout’s opt-out leaves
next buildgreen while child pages keep theirs—actual layout blockers only fire once descendant opt-outs come off! - Clean root first: Un-opt
app/layout.tsx, clear any Sync-IO or client-hook nav blockers, then descend feature by feature.
By default next build exits on the first blocking route. Use these two diagnostic flags when isolating tricky errors:
# Report ALL blocking routes + full file:line traces
npx next build --debug-prerender
# Build ONLY specific file-path globs (NOT URL paths!)
npx next build --debug-prerender --debug-build-paths="app/admin/**/page.tsx"Passing a URL like /admin matches zero files and silently builds nothing.
Two-View Verification with Turbopack next-dev-loop
# 1. Start Turbopack dev server (default in Next.js 16.3+; avoid --webpack) & bind worktree browser session
SESSION="$(agent-browser session id --scope worktree --prefix next-dev-loop)"
agent-browser --session "$SESSION" --restore --enable react-devtools open http://localhost:3000/settings/profile
# 2. Cross-check framework state over /_next/mcp (SSE responses: extract JSON from data: lines)
# • get_compilation_issues → confirms Turbopack compile is clean
# • get_routes → lists app/ route inventory
# • get_page_metadata → reveals exact segment files powering the visited route
# • get_errors / get_logs → catches runtime, hydration, and blocking-prerender errorsVerify in agent-browser that frame 1 renders real navigation, headings, and skeletons—not a blank screen.
Whenever you refactor a shared layout or sidebar component, re-check sibling routes under that layout.
Once green, apply next-cache-components-optimizer to lift shared blocks out of <Suspense> into "use cache".
next build.next while next dev is running (it breaks active incremental state). When a feature passes next-dev-loop, finish with npx next build as your final commit gate before moving to the next feature.
7. Partial Prefetching (partialPrefetching: true)
Legacy Next.js prefetched entire routes per URL. With partialPrefetching: true, default links reuse one shared App Shell across every dynamic parameter, while only opted-in <Link prefetch={true}> links pre-warm cached URL-specific data ahead of entry.
- Audit before enabling: Search
app/and shared components (rg -n '\bprefetch\b|router\.prefetch') for effectiveprefetch={true}links and imperativerouter.prefetch()calls. - Lock legacy baseline: Write and pass
@next/playwrightinstant()tests undernext startwith the flag still OFF. - Stage destinations: Add
export const prefetch = 'partial'to audited routes until every locked test passes again. - Flip flag + codemod: Set
partialPrefetching: trueinnext.config.tsand runnpx @next/codemod@canary remove-partial-prefetch ./app. - Sweep Insights: Visit routes in
next devto clear any remaininginstant-shell-url-datawarnings.
// next.config.ts (after Cache Components is green)
export default {
cacheComponents: true,
partialPrefetching: true,
}
# Strip temporary route exports cleanly after flag flip:
npx @next/codemod@canary remove-partial-prefetch ./appinstant-shell-url-data InsightsgenerateStaticParams routes where params is already inside <Suspense>, but awaited too high above the URL-specific leaf—tying the shared App Shell to a single URL. Push the await params down into its own leaf boundary.
<Link> navigations share a single cached emerald App Shell across infinite dynamic URLs, while explicit <Link prefetch={true}> paths pre-warm golden-green URL-specific data crystals before the click.
8. 5 Real-World Copy-Paste Recipes
Drop these five production-tested patterns straight into Next.js 16.3+ App Router codebases. Every recipe respects non-blocking shell composition and clean mutation boundaries.
| Recipe & Goal | Boundary & Config | Copy-Paste Snippet / Command |
|---|---|---|
| 1. Incremental Route Adoption Starter Safe Team Rollout |
Clean Git treecacheComponents: trueinstant = false markers |
npx @next/codemod@latest cache-components-instant-false ./appSet cacheComponents: true in next.config.ts, remove experimental.dynamicIO, migrate force-static routes first, then run npx next build --debug-prerender. |
2. Promise-Forwarded Dynamic [slug] PageZero Page-Top Await |
Sync page export<Suspense> boundaryForwarded params |
export default function Page({ params }: { params: Promise<{ slug: string }> }) { return <Shell><Suspense fallback={<PostSkeleton />}><PostBody params={params} /></Suspense></Shell>} — await const { slug } = await params strictly inside PostBody. |
| 3. Authenticated Nav Shell (No Hook Block) Fixes Client Hook Error |
Static outer <nav>Isolated client leaf usePathname() |
Keep brand logo and layout links static in RootLayout. Wrap only <ActiveRouteTabs /> (which calls usePathname()/useSearchParams()) and <UserMenu /> inside <Suspense fallback={<NavTabsSkeleton />}> so dynamic routes never hit blocking-prerender-client-hook. |
| 4. Cached Catalog + Mutation Revalidation Rich Static Shell |
"use cache"cacheLife('hours')cacheTag + updateTag |
async function Catalog({ cat }: { cat: string }) { 'use cache'; cacheLife('hours'); cacheTag('cat-' + cat); return <Grid items={await getItems(cat)} />; }In your Server Action: mutate DB, then call updateTag('cat-' + cat) and verify under next start. |
5. Opted-In <Link prefetch={true}> DashboardPre-Click URL Data |
prefetch = 'partial'partialPrefetching: true"use cache" URL slice |
Mark destination with export const prefetch = 'partial' while auditing; move cached URL-keyed summary into "use cache" behind <Link href={'/org/' + id} prefetch={true}>; verify with instant() under next start, then run remove-partial-prefetch. |
params promise into a <Suspense> child (Recipe 2) keeps your shared App Shell reusable across all URLs, while calling a "use cache" data helper inside that child (Recipe 4) lets <Link prefetch={true}> resolve the URL’s cached content before the user even clicks.
9. Regression Proof with @next/playwright instant()
Timers are flaky and next dev does not prefetch. Guard your instant navigations with instant() from @next/playwright—a deterministic dynamic-data lock running against a real production build.
// next.config.ts (gated to E2E/CI test builds)
export default {
cacheComponents: true,
partialPrefetching: true,
experimental: {
exposeTestingApiInProductionBuild:
process.env.PLAYWRIGHT_TEST === '1',
},
}Run tests against next build && next start. Keep @next/playwright on the exact same release version as next.
- Under the lock (
instant()): Dynamic data streams are paused. Your meaningful shell marker MUST be visible (toBeVisible()), and deferred dynamic data MUST still be absent (toHaveCount(0)) to prevent vacuous passes! - After lock release: Dynamic content streams in (
toBeVisible()). - RED → GREEN differential: Prove the test fails RED before your fix, turns GREEN after, and stays non-blank visually.
Production Tests: Soft Client Navigation vs. Hard Initial Load
A. Soft Client Navigation (<Link> Click)
import { test, expect } from '@playwright/test'
import { instant } from '@next/playwright'
test('dashboard soft nav is instant', async ({ page }) => {
await page.goto('/projects')
const link = page.getByTestId('nav-analytics-link')
await expect(link).toBeVisible()
await instant(page, async () => {
await link.click()
await expect(page.getByTestId('analytics-shell')).toBeVisible()
await expect(page.getByTestId('live-metrics')).toHaveCount(0)
})
await expect(page.getByTestId('live-metrics')).toBeVisible()
})B. Hard Initial Load (page.goto + storageState)
// Inject session via storageState — NEVER call page.goto()
// to log in before instant(), or auth runs unmeasured!
test('analytics hard load serves shell', async ({ page }) => {
const url = 'http://127.0.0.1:3000/analytics'
await instant(
page,
async () => {
await page.goto(url)
await expect(page.getByTestId('analytics-shell')).toBeVisible()
await expect(page.getByTestId('live-metrics')).toHaveCount(0)
},
{ baseURL: new URL(url).origin }
)
await expect(page.getByTestId('live-metrics')).toBeVisible()
})exposeTestingApiInProductionBuild was accidentally omitted, instant() silently becomes a no-op and a shell-only assertion passes falsely! Checking toHaveCount(0) on a known dynamic node inside the lock guarantees the lock actually engaged.
10. Cross-Tool Synergy: From Static Shell to Live AI UI
Cache Components and Partial Prefetching form the presentation foundation of modern Vercel applications—pairing edge-delivered App Shells with Runtime Cache, AI SDK 7 streaming interfaces, and automated CI locks.
How These Layers Click Together in a Production AI App
In an AI workspace, the sidebar, model picker, and prompt composer belong in your prerendered App Shell via "use cache", served straight from the Vercel CDN. Only the user’s active conversation history and AI SDK 7 token streams sit inside <Suspense>, so clicking any thread opens immediately.
Tag-based invalidation (updateTag / revalidateTag) coordinates across Next.js "use cache" and Vercel Runtime Cache, while running @next/playwright instant() against preview deployments catches accidental top-level cookies() or await params regressions before merge.
"use cache", and user-specific AI or auth data behind tight <Suspense> bays—every layer of the Vercel platform reinforces the next.
11. Troubleshooting Clinic & Pre-Flight Checklist
Most Cache Components and Partial Prefetching snags trace to one of seven concrete patterns. Match your error below for the ten-second fix, then verify your app against the pre-flight checklist.
| Symptom / Error | Root Cause | 10-Second Fix |
|---|---|---|
1. experimental.dynamicIO aborts startup |
Legacy experimental flag was replaced by top-level cacheComponents in Next.js 16.3+. |
Delete experimental.dynamicIO (and deprecated experimental.useCache) from next.config.* and set top-level cacheComponents: true. |
2. Top-level await params blocks shared shell |
Awaiting params or searchParams before <Suspense> ties the shell to one URL or fails prerender. |
Remove await from the page/layout function; forward the params promise into a <Suspense> child and await it inside that child. |
3. Sync-IO breaks an instant = false route |
new Date(), Date.now(), Math.random(), or crypto.randomUUID() ignores opt-outs. |
Run next build --debug-prerender --debug-build-paths="..." to locate the call; move into "use cache", behind <Suspense>, or use connection(). |
4. cookies() throws inside use cache under next start |
next build passed, but a cached helper called cookies(), headers(), or auth session at runtime. |
Read session/cookies outside "use cache" inside a <Suspense> parent, and pass serializable primitives (like tenantId) as arguments. |
5. Only async functions allowed with "use cache" + instant |
A file with top-level "use cache" also exported const instant = false or read request data. |
Remove file-level "use cache" from the route file; place "use cache" strictly on pure async data/UI functions inside helper modules or components. |
6. Codemod reports 0 ok or misses client-hook error |
Codemod targeted wrong dir (./app vs ./src/app), or a shared nav calls usePathname(). |
Re-run codemod against the real app folder (check count > 0), and wrap usePathname()/useSearchParams() client leaves in <Suspense>. |
7. <Link prefetch={true}> returns shell-only |
Destination lacks export const prefetch = 'partial' (or partialPrefetching: true), or URL data isn’t cached. |
Add export const prefetch = 'partial' during rollout (or enable partialPrefetching: true), wrap URL reads in "use cache", and test under next start. |
6-Point Pre-Flight Checklist Before Merging to Main
experimental.dynamicIO, dynamic, revalidate, or fetchCache exports across app/.export const instant = false markers.next-dev-loop & Insights Clean: Turbopack /_next/mcp reports zero compilation or blocking errors and zero amber Insights warnings.next start Tested: Every new "use cache" boundary, mutation updateTag(), and <Link prefetch={true}> verified under next start.instant() Lock Passing in CI: Both soft-nav and hard-load @next/playwright instant() tests assert shell visible AND deferred content toHaveCount(0).