Part 10 / Stage 3
Caching with Cache Components
Goal: Learn Next.js's caching model exactly as this installed version actually behaves, not as an older tutorial describes it — the
"use cache"directive,cacheLifeprofiles,cacheTag, and the sharp line between what gets baked into the static shell and what stays a request-time read. Built on Mandi Fresh's daily stats, an aggregation query standing in for a real "sum today's orders" SQL query that is genuinely expensive to repeat on every request. Time: ~7 h · Level: finished Part 9 (data fetching,<Suspense>as the escape valve for real-latency reads) Verified against: Next.js 16.4.6 / React 19.3.0,cacheComponents: true+partialPrefetching: true— this install's defaults sincecreate-next-app, confirmed inTOOLING.md.
⚠️ If you've read an older Next.js tutorial about caching: this install ships a separate guide,
node_modules/next/dist/docs/01-app/02-guides/caching-without-cache-components.md, specifically for apps not using this model — confirmingDESIGN-NOTES.md's prediction that this course would need to teach Cache Components as its own thing rather than a patch on the old one. If a tutorial you're reading describesfetch(url, { next: { revalidate: 60 } })or a route's ownexport const revalidate = 60, it is describing that older model, not what this part teaches. The two are not drop-in compatible.
What you will learn
- That nothing is cached by default — an
awaitwith real latency and no"use cache"must live behind<Suspense>, exactly like Part 9's data-fetching pages - The
"use cache"directive, applied to a plain data function (data-level) and to an entire Server Component (UI-level) — and how the two compose cacheLifeprofiles — this install's exact default numbers, read from its own config source, not assumed from memory- A real, reproduced surprise: a short
cacheLifeprofile ('seconds') needs<Suspense>just like genuinely uncached data does, even though it IS using"use cache" cacheTag— what it does, and the honest limit of what this part alone can show you about it- How to read a real
next buildroute table and a real response'sx-nextjs-cache/Cache-Controlheaders to know, for any route, exactly what got cached and for how long
Topics in this part
Practice
Every exercise adds a scratch route under harness/app/mandi/scratch-exN/, runs
a real command against it, and then removes what it added, restoring
app/mandi/ to the exact state Part 10's README ends on. Copy the exact
commands you ran and their real output into your own notes; do not type
output from memory.
A note on
next typegen: deleting a scratch route leaves a stale reference in.next/dev/types/validator.ts. Runnpx next typegenbefore your nextnpm run buildafter deleting a scratch route, or you'll chase a confusing, unrelated-looking type error — the same gotcha Part 9's exercises already found.
Exercise 1: An uncached page, from scratch, in your own words
Scenario: Mandi Fresh wants a live "loading dock" status, the same shape as mandi/live/page.tsx but your own numbers.
What to do: Create app/mandi/scratch-ex1/page.tsx. Write an async component with a 120ms simulated delay that reads new Date().toISOString(), wrap it in <Suspense>, and hit it three times.
Sample output (run for real against this course's harness):
$ for i in 1 2 3; do curl -s http://localhost:PORT/mandi/scratch-ex1 | grep -oE '[0-9]{4}-[0-9:TZ.-]+'; done
2026-12-01T11:41:32.747Z
2026-12-01T11:41:32.898Z
2026-12-01T11:41:33.039Z
$ curl -s -D - -o /dev/null http://localhost:PORT/mandi/scratch-ex1 | grep -iE 'x-nextjs|cache-control'
x-nextjs-stale-time: 300
x-nextjs-prerender: 1
x-nextjs-postponed: 1
Cache-Control: private, no-cache, no-store, max-age=0, must-revalidate
💡 Hint: Three different timestamps, and the exact same private, no-cache, no-store Cache-Control section 1 found for /mandi/live — this is the same shape, your own data.
Exercise 2: Data-level "use cache" with the 'days' profile
Scenario: Prove the cacheLife table in section 3 for a profile the README's own routes never actually use ('hours' and 'default' are the only two covered live).
What to do: Create app/mandi/scratch-ex2/page.tsx with a data function cached via cacheLife("days"), a 400ms simulated delay, and a cacheTag. Hit it three times and read the real build's route table and response headers.
Sample output (run for real against this course's harness):
$ npm run build
...
├ ○ /mandi/scratch-ex2 1d 1w
$ for i in 1 2 3; do curl -s http://localhost:PORT/mandi/scratch-ex2 | grep -oE '[0-9]{4}-[0-9:TZ.-]+'; done
2026-12-01T11:41:05.814Z
2026-12-01T11:41:05.814Z
2026-12-01T11:41:05.814Z
$ curl -s -D - -o /dev/null http://localhost:PORT/mandi/scratch-ex2 | grep -iE 'cache-control'
Cache-Control: s-maxage=86400, stale-while-revalidate=518400
💡 Hint: 86400 is exactly 'days''s revalidate (86400s = 1 day) from the table. 518400 is expire − revalidate = 604800 − 86400, the same subtraction section 3's "going deeper" note worked through for default.
Exercise 3: UI-level "use cache" with no explicit cacheLife
Scenario: Section 4 cached top-categories/page.tsx with "use cache" at the component level but never called cacheLife there either — confirm what profile you get when you don't ask.
What to do: Create app/mandi/scratch-ex3/page.tsx as an async component with "use cache" at its own top (no cacheLife call) that awaits a 450ms simulated supplier-leaderboard read. Measure the first and second request's timing.
Sample output (run for real against this course's harness):
$ npm run build
...
├ ○ /mandi/scratch-ex3 15m 1y
$ curl -s -o /dev/null -w "1st: %{time_total}s\n" http://localhost:PORT/mandi/scratch-ex3
1st: 0.005533s
$ curl -s -o /dev/null -w "2nd: %{time_total}s\n" http://localhost:PORT/mandi/scratch-ex3
2nd: 0.001086s
💡 Hint: 15m/1y in the route table is the default profile, applied with no cacheLife call at all — and both requests are already fast, because next build itself paid the 450ms cost once, at build time (this route has no dynamic params and no <Suspense>, so it's fully static, unlike top-categories only by coincidence of which specific numbers you picked).
Exercise 4: Trigger the real 'seconds'-needs-<Suspense> error yourself
Scenario: Section 3's build error, reproduced from your own mistake instead of copied from the README.
What to do: Create app/mandi/scratch-ex4/page.tsx: a data function cached with cacheLife("seconds"), awaited directly in the page body with no <Suspense> anywhere. Run next build and capture the real error. Delete the file and rebuild clean afterward.
Sample output (run for real against this course's harness):
$ npm run build
...
Error: Route "/mandi/scratch-ex4": Next.js encountered uncached or runtime data during prerendering.
`fetch(...)`, `cookies()`, `headers()`, `params`, `searchParams`, or `connection()` accessed outside of `<Suspense>` prevents the route from being prerendered, blocking the page load and leading to a slower user experience.
Ways to fix this:
- [stream] Provide a placeholder with `<Suspense fallback={...}>` around the data access
- [cache] For uncached data (`fetch`, database calls): cache the access with `"use cache"` (does not apply to `connection()`)
- [block] Set `export const instant = false` to allow a blocking route
...
Export encountered an error on /mandi/scratch-ex4/page: /mandi/scratch-ex4, exiting the build.
💡 Hint: The function genuinely has "use cache" and a real cacheLife profile — that's not enough on its own. 'seconds''s expire (60s) is under the 5-minute prerendering threshold, exactly section 3's finding, now triggered by your own code instead of the README's.
Exercise 5: The 'max' profile's real numbers, read from a response header
Scenario: The cacheLife table in section 3 lists 'max' as 300/2592000/31536000 — confirm the two numbers that actually reach an HTTP client, the same way section 3's "going deeper" note did for default.
What to do: Create app/mandi/scratch-ex5/page.tsx with a data function cached via cacheLife("max"), a 300ms simulated delay. Read its real Cache-Control header.
Sample output (run for real against this course's harness):
$ npm run build
...
├ ○ /mandi/scratch-ex5 30d 1y
$ curl -s -D - -o /dev/null http://localhost:PORT/mandi/scratch-ex5 | grep -i cache-control
Cache-Control: s-maxage=2592000, stale-while-revalidate=28944000
💡 Hint: 2592000 is 'max''s raw revalidate (2592000s = 30 days) — unlike default's expire, 'max''s own expire (31536000s = 1 year) is already at this install's expireTime cap, so nothing gets silently reduced here the way default's INFINITE_CACHE did. 28944000 = 31536000 − 2592000, the same subtraction pattern, confirming it generalizes.
Exercise 6: Does a UI-level cache make its own data-level cache redundant?
Scenario: Section 2 cached a data function; section 4 cached a whole component. Neither example combines both on the same read — find out what happens when you do.
What to do: Create app/mandi/scratch-ex6/page.tsx. Write a data function with its own "use cache" + cacheLife("hours") and a module-level call counter (the same pattern Part 9's stock.ts uses for its counter), then wrap the component that calls it in its own "use cache" + cacheLife("hours") too. Hit it three times and check the counter.
Sample output (run for real against this course's harness):
$ for i in 1 2 3; do curl -s http://localhost:PORT/mandi/scratch-ex6 | grep -o 'calls so far: [0-9]*'; done
calls so far: 1
calls so far: 1
calls so far: 1
💡 Hint: The counter never goes above 1, even across three separate requests — the outer, UI-level cache entry is what actually gets served on requests 2 and 3; the inner, data-level cached function has its own separate cache entry too, but it's never re-invoked because the component wrapping it never re-runs. Caching composes, but the outer cache is the one doing the work once the whole tree is wrapped.
Next
Show the solutions for Part 10 (6 files)
solutions/ex01.tsx
// Solution to Exercise 1. Drop in as harness/app/mandi/scratch-ex1/page.tsx.
// Delete afterward - not part of the harness's canonical Part 10 state.
import { Suspense } from "react";
function wait(ms: number) {
return new Promise<void>((resolve) => setTimeout(resolve, ms));
}
async function DockStatus() {
await wait(120);
return <p id="dock-timestamp">Loading dock checked at: {new Date().toISOString()}</p>;
}
export default function Ex1Page() {
return (
<Suspense fallback={<p id="fallback">Checking the loading dock…</p>}>
<DockStatus />
</Suspense>
);
}
// $ for i in 1 2 3; do curl -s http://localhost:PORT/mandi/scratch-ex1 | grep -oE '[0-9]{4}-[0-9:TZ.-]+'; done
// 2026-12-01T11:41:32.747Z
// 2026-12-01T11:41:32.898Z
// 2026-12-01T11:41:33.039Z
// $ curl -s -D - -o /dev/null http://localhost:PORT/mandi/scratch-ex1 | grep -iE 'x-nextjs|cache-control'
// x-nextjs-stale-time: 300
// x-nextjs-prerender: 1
// x-nextjs-postponed: 1
// Cache-Control: private, no-cache, no-store, max-age=0, must-revalidate
// Confirmed for real against this harness: three different timestamps, and
// the same private/no-store headers section 1's /mandi/live produces.
solutions/ex02.tsx
// Solution to Exercise 2. Drop in as harness/app/mandi/scratch-ex2/page.tsx.
// Delete afterward.
import { cacheLife, cacheTag } from "next/cache";
function wait(ms: number) {
return new Promise<void>((resolve) => setTimeout(resolve, ms));
}
async function getWarehouseAudit() {
"use cache";
cacheLife("days");
cacheTag("mandi-warehouse-audit");
await wait(400);
return { computedAt: new Date().toISOString(), itemsAudited: 312 };
}
export default async function Ex2Page() {
const audit = await getWarehouseAudit();
return (
<p id="audit-computed-at">
Audit computed at: {audit.computedAt} ({audit.itemsAudited} items)
</p>
);
}
// $ npm run build
// ...
// ├ ○ /mandi/scratch-ex2 1d 1w
// $ for i in 1 2 3; do curl -s http://localhost:PORT/mandi/scratch-ex2 | grep -oE '[0-9]{4}-[0-9:TZ.-]+'; done
// 2026-12-01T11:41:05.814Z (identical, all three times)
// 2026-12-01T11:41:05.814Z
// 2026-12-01T11:41:05.814Z
// $ curl -s -D - -o /dev/null http://localhost:PORT/mandi/scratch-ex2 | grep -iE 'cache-control'
// Cache-Control: s-maxage=86400, stale-while-revalidate=518400
// 86400 = 'days' revalidate (1 day). 518400 = 604800 (expire, 1 week) - 86400.
// Confirmed for real against this harness.
solutions/ex03.tsx
// Solution to Exercise 3. Drop in as harness/app/mandi/scratch-ex3/page.tsx.
// Delete afterward.
function wait(ms: number) {
return new Promise<void>((resolve) => setTimeout(resolve, ms));
}
async function getSupplierLeaderboard() {
await wait(450);
return ["Azad Traders", "Nashik Farms Co-op", "Deccan Produce"];
}
// UI-level "use cache", no cacheLife call -> implicit `default` profile,
// same as top-categories/page.tsx in the README's own section 4.
export default async function Ex3Page() {
"use cache";
const suppliers = await getSupplierLeaderboard();
return (
<ol id="suppliers">
{suppliers.map((s) => (
<li key={s}>{s}</li>
))}
</ol>
);
}
// $ npm run build
// ...
// ├ ○ /mandi/scratch-ex3 15m 1y
// $ curl -s -o /dev/null -w "1st: %{time_total}s\n" http://localhost:PORT/mandi/scratch-ex3
// 1st: 0.005533s
// $ curl -s -o /dev/null -w "2nd: %{time_total}s\n" http://localhost:PORT/mandi/scratch-ex3
// 2nd: 0.001086s
// Both fast - the 450ms cost was paid once, at build time, because this
// route has no dynamic params and the "use cache" component has nothing
// left that needs <Suspense> once it's fully static. 15m/1y in the route
// table confirms the `default` profile, applied with zero cacheLife calls.
solutions/ex04.md
# Solution to Exercise 4
**The broken version** — drop in as `harness/app/mandi/scratch-ex4/page.tsx`:
```tsx
import { cacheLife } from "next/cache";
function wait(ms: number) {
return new Promise<void>((resolve) => setTimeout(resolve, ms));
}
async function getFlashSaleCountdown() {
"use cache";
cacheLife("seconds");
await wait(100);
return { secondsLeft: 42 };
}
// No <Suspense> anywhere - "seconds" has expire=60s, under the 5-minute
// threshold, so this should reproduce Part 10 section 3's exact error.
export default async function Ex4Page() {
const sale = await getFlashSaleCountdown();
return <p>{sale.secondsLeft} seconds left</p>;
}
```
Real build error, captured against this harness:
```text
$ npm run build
...
Error: Route "/mandi/scratch-ex4": Next.js encountered uncached or runtime data during prerendering.
`fetch(...)`, `cookies()`, `headers()`, `params`, `searchParams`, or `connection()` accessed outside of `<Suspense>` prevents the route from being prerendered, blocking the page load and leading to a slower user experience.
Ways to fix this:
- [stream] Provide a placeholder with `<Suspense fallback={...}>` around the data access
- [cache] For uncached data (`fetch`, database calls): cache the access with `"use cache"` (does not apply to `connection()`)
- [block] Set `export const instant = false` to allow a blocking route
Learn more: https://nextjs.org/docs/messages/blocking-prerender-dynamic
at body (<anonymous>)
at html (<anonymous>)
Error occurred prerendering page "/mandi/scratch-ex4". Read more: https://nextjs.org/docs/messages/prerender-error
Export encountered an error on /mandi/scratch-ex4/page: /mandi/scratch-ex4, exiting the build.
⨯ Next.js build worker exited with code: 1 and signal: null
```
**Cleanup — delete the file, then rebuild clean:**
```text
$ rm -rf app/mandi/scratch-ex4
$ npx next typegen
Generating route types...
✓ Types generated successfully
$ npm run build
...
✓ Generating static pages using 17 workers (60/60) in ...ms
```
The function genuinely has `"use cache"` and a real `cacheLife` profile —
that alone isn't enough. `'seconds'`'s `expire` (60s) sits under the
5-minute prerendering threshold the installed `cacheLife.md` documents, so
Cache Components excludes it from the static shell and demands a `<Suspense>`
boundary the same as genuinely uncached data would need. Wrapping the
component in `<Suspense>` (the fix, not shown here, is Exercise 1/Part 10
section 3's own `stats/fast/page.tsx`) is the real correction — this
exercise's whole point is triggering the error yourself, not fixing it.
solutions/ex05.tsx
// Solution to Exercise 5. Drop in as harness/app/mandi/scratch-ex5/page.tsx.
// Delete afterward.
import { cacheLife } from "next/cache";
function wait(ms: number) {
return new Promise<void>((resolve) => setTimeout(resolve, ms));
}
async function getAnnualForecast() {
"use cache";
cacheLife("max");
await wait(300);
return { computedAt: new Date().toISOString() };
}
export default async function Ex5Page() {
const forecast = await getAnnualForecast();
return <p id="forecast-computed-at">Forecast computed at: {forecast.computedAt}</p>;
}
// $ npm run build
// ...
// ├ ○ /mandi/scratch-ex5 30d 1y
// $ curl -s -D - -o /dev/null http://localhost:PORT/mandi/scratch-ex5 | grep -i cache-control
// Cache-Control: s-maxage=2592000, stale-while-revalidate=28944000
// 2592000 = 'max' revalidate (30 days). Unlike `default`'s expire (which is
// capped at this install's 1-year expireTime before it reaches a header),
// 'max's own raw expire (31536000s = 1 year) IS already at that cap, so
// nothing gets silently reduced here. 28944000 = 31536000 - 2592000,
// confirmed for real against this harness.
solutions/ex06.tsx
// Solution to Exercise 6. Drop in as harness/app/mandi/scratch-ex6/page.tsx.
// Delete afterward.
// Combines a data-level "use cache" function with a UI-level "use cache"
// component wrapping it, to see whether the two compose or conflict.
import { cacheLife } from "next/cache";
function wait(ms: number) {
return new Promise<void>((resolve) => setTimeout(resolve, ms));
}
let dataCalls = 0;
async function getPriceIndex() {
"use cache";
cacheLife("hours");
dataCalls++;
await wait(250);
return { index: 104.2, calls: dataCalls };
}
export default async function Ex6Page() {
"use cache";
cacheLife("hours");
const priceIndex = await getPriceIndex();
return (
<p id="price-index">
Price index: {priceIndex.index} (data fn calls so far: {priceIndex.calls})
</p>
);
}
// $ for i in 1 2 3; do curl -s http://localhost:PORT/mandi/scratch-ex6 | grep -o 'calls so far: [0-9]*'; done
// calls so far: 1
// calls so far: 1
// calls so far: 1
// Confirmed for real against this harness: the counter never passes 1
// across three separate requests. The outer, UI-level cache entry is what
// actually answers requests 2 and 3 - the inner data-level cache has its
// own separate entry too, but it's never re-invoked because the component
// wrapping it never re-runs. Caching composes, but the OUTER cache is the
// one doing the work once the whole tree is wrapped in "use cache".
Common mistakes
| Mistake | Why it is wrong | Fix |
|---|---|---|
Assuming cacheComponents: true caches things by default |
It's the opposite — it strictly enforces that nothing with real timing can prerender without an explicit decision, proven in section 1 | Add "use cache" (this part) or <Suspense> (Part 7/9) — one of the two, deliberately |
Expecting every cacheLife profile to behave the same way at build time |
'seconds' genuinely needs <Suspense> even with "use cache" present — a short expire makes it a "dynamic hole," verified in section 3 |
Check cacheLife.md's prerendering-behavior thresholds for the profile you picked, not just its name |
Reading an older tutorial's export const revalidate = 60 or fetch(url, { next: { revalidate } }) as current |
This install's own docs name that the "previous model," documented separately for apps not using Cache Components | Use "use cache" + cacheLife() instead, as this part does throughout |
Treating default's "never expires" as literally infinite in a response |
Capped at this install's expireTime (1 year) before it reaches a header — verified in section 3's going-deeper note |
Read the actual header or route table, don't assume the raw INFINITE_CACHE constant is what ships |
Calling cacheTag() and expecting it to do something visible on its own |
A tag only matters once something calls revalidateTag() with it — Part 11's subject, not this one |
Tag now with a specific, actionable name; invalidate later |
Quick recap
- Nothing is cached by default — uncached, real-latency data needs
<Suspense>, same rule Part 9 already established. "use cache"+cacheLife()+cacheTag()caches a function's (or a whole component's) result and gives it a lifetime — verified with identical timestamps across repeated requests and realx-nextjs-cache: HIT/Cache-Controlheaders.- This install's real
cacheLifedefault profiles, read fromconfig-shared.js:default(300/900/∞-capped-at-1y),seconds(30/1/60),minutes(300/60/3600),hours(300/3600/86400),days,weeks,max. - A short enough
cacheLife('seconds',expireunder 5 minutes) excludes a cache entry from prerendering — it needs<Suspense>just like genuinely uncached data, a real finding reproduced against this harness, not assumed from the profile's name. "use cache"works at the data level (one function) or the UI level (a whole component) — both verified, both land in the real build's route table as○(Static).cacheTagis set up now, used (viarevalidateTag) starting next part.- An older tutorial's
fetchcache options orexport const revalidatedescribe a different, separately-documented model in this exact installed version — not interchangeable with what this part teaches.
Checklist
- I built an uncached page behind
<Suspense>and confirmed its timestamp changes on every request, with realCache-Control: private, no-storeheaders. - I cached a data function with
"use cache"+cacheLife('hours')and proved — with three identical timestamps and a realx-nextjs-cache: HITheader — that it only actually ran once. - I can state this install's real
stale/revalidate/expirenumbers for at least twocacheLifeprofiles, sourced fromconfig-shared.js, not guessed. - I reproduced the
cacheLife('seconds')-needs-<Suspense>build error myself and explained it using thecacheLife.mdprerendering-behavior thresholds. - I cached an entire Server Component (not just a data function) with
"use cache"and measured the real speed difference between the first and second request. - I can explain what
cacheTagdoes and does not do on its own, without Part 11. - I read a real
next buildroute table and matched each of this part's four routes to its○/◐symbol and why.