Skip to content

Lesson 12 of 27Full-stack

Cache Components in Depth

The Cache Components model beyond the basics: cache keys, in-memory vs remote vs private caches, custom handlers, lifetimes, ensureStatic, debugging and migration.

18 min read0/5 questions

You turn on cacheComponents in a three-year-old app and next build fails on 40 routes. Or you self-host on six containers and notice the database gets hit as if nothing were cached. Or a teammate asks whether export const revalidate = 3600 still works. All three need more than the basics from Data Fetching and Caching: how a cache entry is keyed, where it is stored, how lifetimes combine, how to guarantee a route stays static, and how to migrate without stopping feature work. This is the lesson for the engineer who owns caching on the team.

The model in one paragraph

With Cache Components, everything is dynamic by default and you opt in to caching. Every part of the tree ends up in one of three states. Static: pure markup and synchronous code, prerendered into the shell. Cached: an async function or component marked "use cache", with a lifetime from cacheLife; its output can be prerendered too. Dynamic: anything that reads runtime data (cookies(), headers(), searchParams, unknown params) or does uncached I/O; it must sit inside <Suspense> and streams at request time. Think of "use cache" as Cache-Control for a component: the cacheLife comment in the type definitions even maps it that way, with stale like max-age in the browser, revalidate like s-maxage on the server, and the gap up to expire like stale-while-revalidate.

It has been stable since 16.0, new create-next-app projects turn it on, and the docs plan it as the behaviour for every app in the next major version. Enable it with Partial Prefetching (from Streaming, Loading UI and Instant Navigations):

next.config.ts
import type { NextConfig } from "next";
 
const nextConfig: NextConfig = {
  cacheComponents: true,
  partialPrefetching: true, // leaving it unset logs a warning
};
 
export default nextConfig;

Two requirements surprise people. Cache Components needs the Node.js runtime: remove any export const runtime, including "edge". And the old flags experimental.ppr, experimental.dynamicIO and experimental.useCache are gone; cacheComponents replaces all of them.

How an entry is keyed

A "use cache" entry's key is built from four things:

  1. The build ID (or deploymentId if you set one). A new deploy means new keys, so no use cache entry survives a deploy, even in a remote store. This is deliberate: the function's code or return shape may have changed.
  2. The function ID, a hash of where the function lives and its signature.
  3. The serialized arguments (props, for a component), plus any variables the function captures from outer scopes, which are bound as hidden arguments.
  4. In development only, an HMR hash, so editing code invalidates.

Arguments must be serializable: primitives, plain objects, arrays, Date, Map, Set, typed arrays. Class instances, functions, symbols and URL objects are not. JSX can be returned, and children or a Server Action can be passed through as long as the cached function does not read them; they are not part of the key. That pass-through rule is how a cached layout can wrap uncached children.

Also note: React.cache values set outside a "use cache" scope are invisible inside it, so pass data as arguments.

Key design is where seniors earn their keep. Every unique argument value creates a separate entry. Run this simulation of 1,000 product-list requests with a category and a price filter:

TypeScriptcache-keys.ts
type Req = { category: string; minPrice: number };let seed = 7;const rand = (n: number) => { seed = (seed * 1103515245 + 12345) % 2147483648; return Math.floor(seed / 65536) % n; };const requests: Req[] = Array.from({ length: 1000 }, () => ({ category: `cat-${rand(5)}`, minPrice: rand(200),})); function simulate(label: string, keyOf: (r: Req) => string, instances = 1) { const caches = Array.from({ length: instances }, () => new Set<string>()); let hits = 0; requests.forEach((r, i) => { const cache = caches[i % instances]; // round-robin load balancer const key = keyOf(r); if (cache.has(key)) hits++; else cache.add(key); }); const entries = caches.reduce((n, c) => n + c.size, 0); console.log(`${label.padEnd(40)} hit rate ${(hits / 10).toFixed(1)}%, ${entries} entries`);} simulate("key: category + minPrice, 1 server", (r) => `${r.category}|${r.minPrice}`);simulate("key: category only, 1 server", (r) => r.category);simulate("key: category + minPrice, 6 servers", (r) => `${r.category}|${r.minPrice}`, 6);simulate("key: category only, 6 servers", (r) => r.category, 6);
Output
Press Run (⌘ Enter) to see what happens.

Caching on the price filter fragments the cache into over 600 entries and only about a third of requests hit. Spread the same traffic over six separate in-memory caches and the hit rate falls under 10%. Caching on the low-cardinality dimension (category) and filtering the price in memory after the lookup gives a near-perfect hit rate. The same principle applies to users: do not cache getHomeContent(userId); read the user's language from the cookie and cache getHomeContent(language).

Where entries live: default, remote and private

The directive decides the storage, and the storage decides your hit rate.

  • "use cache" stores entries in the default handler, an in-memory LRU inside each Next.js process. Entries filled at build time become part of the static shell no matter what. At runtime, a self-hosted server keeps entries across requests (size it with cacheMaxMemorySize); on serverless, instances are short-lived, so runtime hits are rare.
  • "use cache: remote" stores entries in the remote handler: a shared store such as Redis that every instance reads. Hosting platforms usually provide one; when self-hosting you configure it. You pay a network round trip per lookup and storage costs, so it earns its place for request-time content that is expensive, rate-limited or flaky upstream. It is wasted on data that is already fast (under about 50ms), changes every few seconds, or has near-unique keys per request.
  • "use cache: private" is the escape hatch for functions that must read cookies(), headers() or searchParams directly. Results are never stored on the server across production requests; they deduplicate within a request and live in the browser's memory for the stale time. Its stale must be at least 30 seconds for per-link prefetches to use it and at least 5 minutes to land in the App Shell. Reach for it only when you cannot refactor to pass the value as an argument, or when compliance says per-user data must not sit in a shared server cache. It has no configurable handler.
use cacheuse cache: remoteuse cache: private
Server storageIn-memory per process (or your default handler)Shared remote handlerNone
Shared between usersYesYesNo, per browser
Can read cookies or headersNo, pass values inNo, pass values inYes
Extra costNoneNetwork lookup, storageNone
Survives a deployNoNoNot applicable

Nesting is restricted: a remote cache can sit inside a regular or another remote cache, but remote and private caches cannot be nested inside each other in either direction. If you need entries that survive deploys (rare, and risky if the shape changes), the older unstable_cache and the fetch cache still persist across deployments.

Quick check
You self-host on four containers. The home page greeting comes from a CMS keyed by the user's language cookie, the CMS is rate-limited, and the content changes a few times a day. What is the best fit?
Need a nudge? A hint rules out a wrong answer.

Custom cache handlers for self-hosting

Configure handlers by name in next.config.ts. default backs "use cache", remote backs "use cache: remote", and any extra name you add becomes "use cache: <name>":

next.config.ts
import type { NextConfig } from "next";
 
const nextConfig: NextConfig = {
  cacheComponents: true,
  partialPrefetching: true,
  cacheHandlers: {
    remote: require.resolve("./cache-handlers/redis-handler.js"),
  },
};
 
export default nextConfig;

A handler implements five methods from the CacheHandler type (exported by next/cache): get and set for entries, plus refreshTags, getExpiration and updateTags for invalidation. Two details bite. An entry's value arrives as a ReadableStream that can be read only once, so consume it in set() and build a fresh stream in every get(). And tag invalidation must be distributed: when one instance runs revalidateTag, updateTags() should write the invalidation time to shared storage, and refreshTags() (called once per request before the first read) should pull recent invalidations so every instance agrees. Before writing one, look for a maintained handler for your store and read the reference implementation linked from the cacheHandlers docs.

Six requests across three self-hosted instances
Load balancer: round robinLoad balancerround robinInstance A: in-memory LRUInstance Ain-memory LRUInstance B: in-memory LRUInstance Bin-memory LRUInstance C: in-memory LRUInstance Cin-memory LRURedis: remote handlerRedisremote handlerPostgresPostgresget / seton a miss

Requests are spread across instances. With plain use cache, each instance fills its own memory, so the same entry is computed up to three times, and a restart or deploy empties it.

1/4

Lifetimes: custom profiles, thresholds and nesting

Data Fetching and Caching listed the built-in cacheLife profiles. Real codebases define their own names in next.config.ts, so intent is readable at the call site and one change updates every caller:

next.config.ts
const nextConfig = {
  cacheComponents: true,
  cacheLife: {
    editorial: { stale: 600, revalidate: 3600, expire: 86400 }, // seconds
    pricing: { stale: 60, revalidate: 300, expire: 3600 },
  },
};

Then call cacheLife("editorial"). Omitted fields inherit from default, and the generated types autocomplete your names. Redefining default changes every use cache that never calls cacheLife, so document it if you do.

Lifetimes decide where cached output can be delivered from, not only how long it lives:

  • revalidate: 0 or expire under 5 minutes: left out of prerenders entirely. It becomes a dynamic hole resolved per request, so it needs a Suspense boundary.
  • stale under 30 seconds: also left out of prerenders, because a prefetch would expire before the user clicked.
  • stale from 30 seconds up to 5 minutes: prerendered, but kept out of the App Shell.

The browser's router also enforces a minimum stale time of 30 seconds regardless of what you configure, and any updateTag, revalidateTag, revalidatePath or refresh() called from a Server Action clears the whole client cache at once.

Predict the outputTypeScript

What does this print?

type Life = { stale: number; revalidate: number; expire: number };
function placement(l: Life) {
if (l.revalidate === 0 || l.expire < 300) return "dynamic hole";
if (l.stale < 30) return "dynamic hole";
if (l.stale < 300) return "prerender, not App Shell";
return "App Shell";
}
// the built-in "seconds" profile
console.log(placement({ stale: 30, revalidate: 1, expire: 60 }));
Need a nudge? Hints walk you through it.

Nesting rules. When a cached function calls another cached function, an explicit cacheLife on the outer one always wins, longer or shorter. Without one, the outer uses default (15-minute revalidate), shorter inner lifetimes pull it down, and longer inner lifetimes cannot extend it. That makes behaviour depend on code you are not looking at, possibly inside a dependency. So Next.js refuses one case outright: a short-lived inner cache (say cacheLife("seconds")) inside an outer use cache with no explicit cacheLife fails the prerender. The fix is the habit you should have anyway: call cacheLife explicitly in every use cache scope.

Quick check
A cached ProductPage calls cacheLife('days'). Inside it, a cached PriceBadge calls cacheLife('minutes'). How long can the page's cache entry be reused?
Need a nudge? A hint rules out a wrong answer.

Guaranteeing static output: ensureStatic (16.4)

Teams often promise that a route stays static, like a marketing page served from a CDN. Six months later someone adds cookies() to a shared header and the promise silently breaks. Next.js 16.4 adds the ensureStatic segment config to turn that promise into a check. Export it from a page or layout:

ValueWhat must be static
"auto" (default)Nothing extra
"shell"The App Shell that a default Link prefetches
"prefetch"The App Shell and per-link prefetches
"navigation"The complete server-rendered route

"navigation" is the strict one, and the only one validated in both next dev and next build. It fails on uncached data, on connection(), on runtime data (even inside Suspense), on caches with expire under 5 minutes, stale under 30 seconds or revalidate: 0, and on passing a request-dependent promise to a Client Component. A dynamic route under it must export generateStaticParams that returns at least one complete set of params. Client Components may still load data in the browser. "shell" and "prefetch" only mean something with Partial Prefetching on.

Levels combine down the tree: a child may set a stricter level than its layout, never a weaker one (the build says so), and false explicitly marks a segment as not meant to be static. Do not confuse it with instant: instant checks that a navigation can show UI immediately, while ensureStatic checks that no request-time server work happens.

Debugging the build

The errors you will see while adopting are specific, so learn to read them.

  • Route "/dashboard": Next.js encountered runtime data during prerendering. or ...encountered uncached data during prerendering. The message lists fixes: wrap the access in <Suspense>, cache it with "use cache" (not possible for connection()), or set export const instant = false to allow a blocking route for now.
  • Synchronous I/O. new Date(), Date.now(), Math.random() or crypto.randomUUID() during prerender fail the build, and instant = false does not clear them. Move the call behind await connection() inside Suspense, or into a Client Component.
  • A build that hangs, then times out after about 50 seconds with Filling a cache during prerender timed out. Something inside a "use cache" awaits a promise of runtime data: a cookies() promise passed as a prop, a captured params, or a shared Map of in-flight fetches. Await outside, pass plain values in.
  • next-request-in-use-cache. A cached function, or any helper it calls, read cookies() or headers(). On a dynamic route this can pass next build and only fail under next start, so test production builds.

Tools: next build --debug-prerender gives full stack traces (never deploy that build), NEXT_PRIVATE_DEBUG_CACHE=1 logs cache behaviour, and in development logs from cached functions carry a Cache prefix.

Migrating an existing app

Turning on the flag makes route segment configs such as dynamic, revalidate and fetchCache errors, so start there.

Old patternWith Cache Components
export const dynamic = "force-dynamic"Delete it. Uncached work is already per request.
export const dynamic = "force-static""use cache" plus cacheLife("max"); add ensureStatic = "navigation" if it must stay static
export const revalidate = 3600"use cache" plus cacheLife("hours") around the data or UI
fetch(url, { next: { revalidate, tags } })A "use cache" function with cacheLife and cacheTag around the fetch
unstable_cache(fn, keys, opts)Still works; migrate later. The new version needs no key array.
noStore()Delete it; use connection() if work must run per request
generateStaticParams returning []Return at least one real param, or the build errors
export const dynamicParams = falseDelete it; call notFound() for unknown params
revalidateTag(tag)revalidateTag(tag, "max"), or updateTag(tag) in a Server Action

One behaviour change to flag in review: force-static used to make cookies() and headers() return empty values. ensureStatic does not; it fails the build instead, which is safer but means you must remove those reads.

You do not have to migrate everything in one pull request. The supported path is incremental:

Put it in order5 steps

Put an incremental Cache Components migration in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
Match the pairs0/5 matched

Match each symptom to its most likely cause.

Choose an item, then its match on the other side.
Key terms
Cache Components
The Next.js 16 model enabled by cacheComponents: true: dynamic by default, opt-in caching with use cache, and a prerendered static shell.
cache key
Build ID, function ID and serialized arguments (including captured variables) of a use cache function. Any change makes a new entry.
use cache: remote
A directive that stores entries in a shared remote handler, so all server instances share hits. Costs a network lookup.
use cache: private
A directive for functions that read cookies or headers. Never stored on the server across requests; cached in the browser for its stale time.
cache handler
The storage behind use cache (named default) or use cache: remote (named remote), configured with cacheHandlers.
ensureStatic
A 16.4 segment config (shell, prefetch, navigation) that fails validation if the chosen output would need request-time server work.
dynamic hole
Part of a route left out of the prerender, such as uncached data or a cache with expire under 5 minutes. It streams per request.