Cache Components: use cache, cacheLife and cacheTag
A version-qualified path through the Next.js App Router: server components, client boundaries, data fetching, caching layers, streaming, error handling, proxy, images, performance, testing and deployment, with the Next.js 15 and 16 behavior changes called out where they matter.
What you will be able to do
#- Enable and reason about Cache Components and its prerender validation.
- Cache components and functions with use cache, choosing cacheLife profiles deliberately.
- Choose correctly between updateTag, revalidateTag with a profile, and revalidatePath.
Overview
#One model instead of four
Cache Components is the Next.js 16 caching model, enabled with cacheComponents: true in next.config. New create-next-app projects enable it by default. It replaces the implicit multi-layer behavior with one rule: a route prerenders unless it reads uncached or runtime data, and any request-time read must be explicit, either wrapped in use cache or rendered inside a Suspense boundary. Prerender validation enforces this at build time, so a page that reads cookies() or searchParams outside Suspense fails the build with a named error instead of silently turning dynamic.
// next.config.ts
const nextConfig: NextConfig = { cacheComponents: true };
The use cache directive
'use cache' marks a function, component, or whole file as cacheable. Cached things must be async. Without extra configuration the default profile applies; cacheLife() selects a preset or custom profile, and cacheTag() attaches invalidation handles:
import { cacheLife, cacheTag } from 'next/cache';
export async function getTask(id: string) {
'use cache';
cacheLife('hours');
cacheTag('tasks', `task-${id}`);
return getTaskById(id);
}
Preset profiles pair stale, revalidate and expire: default is stale 5 minutes, revalidate 15 minutes, no expiration; seconds, minutes, hours, days, weeks and max scale up; custom profiles are declared in next.config under cacheLife. Stale is how long clients may reuse the value without checking; revalidate is the background regeneration cadence; expire is the hard ceiling.
Invalidation choice
After a mutation, pick by required freshness: updateTag('tasks') inside a Server Action for read-your-own-writes, expiring immediately so the next request waits for fresh data; revalidateTag('tasks', 'max') for stale-while-revalidate where a profile argument is required in Next.js 16; revalidatePath('/tasks') to discard rendered output for a path. For uncached live data, no directive: wrap the component in Suspense so its request-time read streams while the prerendered shell ships instantly. This shell-plus-stream split is what Cache Components formalizes.
Exercises
#Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.
Exercise 1Predict
With cacheComponents enabled, this page fails prerender validation. Why, and what are the two sanctioned fixes? export default async function Page({ searchParams }: { searchParams: Promise<{ q: string }> }) { const { q } = await searchParams; const results = await search(q); return <Results data={results} />; }
Exercise 2Explain
Explain the three timing knobs of a cacheLife profile (stale, revalidate, expire) using a news homepage as the example, and pick a preset for it with justification.
Reveal the reference answer
reference.textStale is how long a delivered value may be reused without rechecking the server; revalidate is how often the server regenerates the value in the background; expire is the hard age limit after which the value must be regenerated before serving. For a news homepage, content updates throughout the day but a few minutes of staleness is acceptable: cacheLife('minutes') (stale 5 minutes, revalidate 1 minute, expire 1 hour) fits, because readers get fast responses within the stale window, the server refreshes continuously, and nothing older than an hour is ever served. The default profile (revalidate 15 minutes) would risk hour-old headlines; 'seconds' would regenerate far more than the content changes.Authored expected output: Three definitions plus a justified preset choice.
Choosing a profile is a product staleness decision, not a performance guess.
Exercise 3Implement
With Cache Components enabled, implement: a cached getPost(id) with a per-id tag and a list tag, a Server Action editPost that makes the user's own edit visible immediately, and a webhook-facing Route Handler that invalidates with stale-while-revalidate semantics.
starter.ts// lib/posts.ts // TODO: getPost with use cache, cacheLife('days'), cacheTag // app/actions.ts // TODO: editPost with read-your-own-writes invalidation // app/api/revalidate/route.ts // TODO: POST handler with revalidateTag and a profileReveal the reference answer
reference.ts// lib/posts.ts import { cacheLife, cacheTag } from 'next/cache'; export async function getPost(id: string) { 'use cache'; cacheLife('days'); cacheTag('posts', `post-${id}`); return db.post.findUnique({ where: { id } }); } // app/actions.ts 'use server'; import { updateTag } from 'next/cache'; export async function editPost(id: string, data: PostInput) { await db.post.update({ where: { id }, data }); updateTag(`post-${id}`); } // app/api/revalidate/route.ts import { revalidateTag } from 'next/cache'; export async function POST() { revalidateTag('posts', 'max'); return Response.json({ ok: true }); }Authored expected output: Editor sees their own change immediately; webhook invalidation refreshes in the background without blocking readers.
updateTag is Server-Actions-only by design: read-your-own-writes is an interactive contract, while webhooks have no user waiting.
Exercise 4Debug
Under Cache Components, this cached function never serves fresh values after an edit, even though revalidateTag is called. Find the bug. export async function getPost(id: string) { 'use cache'; cacheLife('days'); return db.post.findUnique({ where: { id } }); } // action revalidateTag('posts', 'max');
starter.tsexport async function getPost(id: string) { 'use cache'; cacheLife('days'); return db.post.findUnique({ where: { id } }); } // action revalidateTag('posts', 'max');Reveal the reference answer
reference.tsThe cached function never calls cacheTag, so nothing links its cache entries to the 'posts' tag; revalidateTag expires tags, not functions. Add cacheTag('posts', `post-${id}`) inside the use cache scope. Per-id tags let the edit action expire just the edited post with updateTag(`post-${id}`), while the list tag 'posts' covers index pages.Authored expected output: After adding cacheTag, invalidation reaches the cached entries.
Tagging is the join between cached data and invalidation calls; omitting it silently disables invalidation.
Exercise 5Test
Write a pure function servingDecision(profile: { stale: number; revalidate: number; expire: number }, ageSeconds: number) returning 'client-stale-ok' when age is within stale, 'serve-and-refresh' when within expire, 'must-regenerate' when age exceeds expire. Use the profile { stale: 300, revalidate: 900, expire: 3600 }; the default profile has no expiry, so it can never reach must-regenerate. Assert at ages 100, 600 and 1e12.
starter.tsexport function servingDecision( profile: { stale: number; revalidate: number; expire: number }, ageSeconds: number, ): 'client-stale-ok' | 'serve-and-refresh' | 'must-regenerate' { // TODO }Reveal the reference answer
reference.tsexport function servingDecision( profile: { stale: number; revalidate: number; expire: number }, ageSeconds: number, ): 'client-stale-ok' | 'serve-and-refresh' | 'must-regenerate' { if (ageSeconds <= profile.stale) return 'client-stale-ok'; if (ageSeconds <= profile.expire) return 'serve-and-refresh'; return 'must-regenerate'; } // revalidate is the regeneration cadence during the serve-and-refresh phase; it does not bound serving by itself.Authored expected output: 100 gives client-stale-ok, 600 gives serve-and-refresh, 1e12 gives must-regenerate.
Modeling the three knobs as a decision function exposes how they interact.
Exercise 6Interview
An interviewer asks: what problem does Cache Components solve compared to the older caching model, and what does it cost? Answer with the mechanism, one migration pain, and when you would not enable it.
Reveal the reference answer
reference.textMechanism: the older model had four interacting caches with implicit defaults, so rendering mode was an emergent property nobody could state precisely. Cache Components makes it explicit: routes prerender unless they access uncached or runtime data, that access must live inside Suspense or a use cache scope, and build-time validation enforces it. The result is composable: one route can ship a prerendered shell, cached sections, and request-time sections. Migration pain: existing routes that quietly read cookies or searchParams at the top now fail validation, so teams must restructure pages into shell plus suspended children, and revalidateTag calls need the new profile argument. When not to enable it yet: a legacy codebase mid-migration where the validation errors would block shipping, or apps pinned to the previous model's semantics, since the config flag is opt-in for existing projects even though new create-next-app apps default to it.Authored expected output: Explicitness benefit, a concrete migration pain, and an honest opt-out scenario.
Cost awareness distinguishes adopters from spectators.
Common misconceptions
#- use cache is the same as the Data Cache. It is the Cache Components directive model; it applies to components and functions, not just fetch, and requires the config flag.
- cacheLife('hours') means the value is served for an hour without checks. It sets revalidate cadence and expire ceiling; stale (5 minutes by default) governs client reuse.
- revalidatePath and revalidateTag are interchangeable. One discards rendered output for a path; the other expires tagged data wherever it is used.
- Cache Components makes everything dynamic. It makes dynamic access explicit: prerender what can prerender, and isolate request-time reads in Suspense.
Follow-up practice
#- nextjs-static-dynamic-rendering
- nextjs-server-actions
Your progress
#Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.
Verification: authored. Answers and outputs on this page are authored reference material, not executed results.