Part 11 / Stage 3
Revalidation
Goal: Stop waiting for a cache entry's own
cacheLifewindow and invalidate it on demand instead —revalidatePathfor an entire route,revalidateTagfor every cache entry carrying a specific tag, andupdateTagfor the "the user must see their own change right now" case. Built on Udupi Grande, a Koramangala darshini whose menu price and review list are both real, mutable data Part 10 only ever tagged, never invalidated. Time: ~6 h · Level: finished Part 10 ("use cache",cacheLife,cacheTag) 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 revalidation:
export const revalidate = 60andfetch(url, { next: { revalidate: 60 } })describe Incremental Static Regeneration (ISR) as it works without Cache Components — a real, still-documented model (node_modules/next/dist/docs/01-app/02-guides/incremental-static-regeneration.mdin this install), but not the one this harness uses. Section 6 reproduces, for real, exactly what happens when that older config meetscacheComponents: true.
What you will learn
- The two kinds of revalidation this install's own internals document — time-based (
cacheLife's own stale-while-revalidate window, already built in Part 10) and on-demand (revalidatePath/revalidateTag/updateTag, this part's subject) — and how they differ in what a request actually experiences revalidatePath: invalidate everything cached under one route path, verified with real build-time vs. post-revalidation timingrevalidateTagwith the recommended"max"profile: stale-while-revalidate on demand — the next request after calling it still gets the old value, fast, while a fresh one computes in the backgroundrevalidateTagwith{ expire: 0 }: the blocking alternative, for when stale content must never be served againupdateTag: the Server-Action-only sibling that skips the stale window entirely, for genuine read-your-own-writes- Why the pre-Cache-Components
export const revalidateroute segment config isn't just "the old way" — it's an install-enforced build error under this harness's config, reproduced for real - Reading
x-nextjs-cacheandx-action-revalidatedresponse headers to know exactly what a given request actually did, instead of guessing from timing alone
Topics in this part
Practice
Every exercise adds a scratch Route Handler under harness/app/api/, runs a
real command against it, and then removes what it added. Copy the exact
commands you ran and their real output into your own notes; do not type
output from memory.
Exercise 1: revalidatePath on a tagged route
Scenario: Section 2 used /mandi/top-categories, which has no cacheTag at all. Prove revalidatePath works identically on a route that does have one — /mandi/stats (Part 10, cacheTag("mandi-daily-stats"), cacheLife("hours")).
What to do: Create app/api/mandi/revalidate-stats/route.ts, a POST handler calling revalidatePath("/mandi/stats"). Warm the route, measure two fast requests, call the handler, then measure the next two.
Sample output (run for real against this course's harness):
$ curl -s -o /dev/null -w "1st:%{time_total}s\n" http://localhost:PORT/mandi/stats
1st:0.009730s
$ curl -s -o /dev/null -w "2nd:%{time_total}s\n" http://localhost:PORT/mandi/stats
2nd:0.001613s
$ curl -s -X POST http://localhost:PORT/api/mandi/revalidate-stats
{"revalidated":true,"path":"/mandi/stats"}
$ curl -s -o /dev/null -w "after-revalidate:%{time_total}s\n" http://localhost:PORT/mandi/stats
after-revalidate:0.665855s
$ curl -s -o /dev/null -w "after-that:%{time_total}s\n" http://localhost:PORT/mandi/stats
after-that:0.001895s
💡 Hint: revalidatePath doesn't care whether the route has a cacheTag — it invalidates by path. The 600ms-ish request right after the call is the real aggregation query (Part 10, section 2) re-running.
Exercise 2: A revalidateTag window that's neither "max" nor { expire: 0 }
Scenario: Section 3 used "max" (effectively a full year of stale-serving); section 4 used { expire: 0 } (none at all). Try a window in between.
What to do: Create app/api/swiggy-menu/revalidate-ten/route.ts, calling revalidateTag("swiggy-menu", { expire: 10 }) after changing a price. Poll /swiggy-menu at a few points: immediately, a few seconds in, and past 10 seconds.
Sample output (run for real against this course's harness):
$ curl -s -X POST http://localhost:PORT/api/swiggy-menu/revalidate-ten -d '{"id":"m1","price":55}'
{"revalidated":true,"item":{"id":"m1","name":"Masala Dosa","price":55,"available":true}}
$ curl -s http://localhost:PORT/swiggy-menu | grep -o '₹<!-- -->[0-9]*' # immediately after
₹90
$ sleep 5
$ curl -s http://localhost:PORT/swiggy-menu | grep -o '₹<!-- -->[0-9]*' # 5s later - already fresh
₹55
$ sleep 7
$ time curl -s http://localhost:PORT/swiggy-menu | grep -o '₹<!-- -->[0-9]*' # 12s later - still 55, but this request took:
real 0m0.545s
💡 Hint: The price is already fresh well before the 10-second expire window even ends — a background revalidation can complete long before expire forces a blocking recompute. The slow request at the 12-second mark proves the 10-second window really did lapse: with nothing left to serve as "stale," this request blocked and recomputed, even though the recomputed value (55) happened to match what was already showing.
Exercise 3: What actually happens if you call updateTag from a Route Handler
Scenario: The README states updateTag is Server-Action-only. Trigger the real enforcement yourself instead of taking the docs' word for it.
What to do: Create app/api/swiggy-menu/update-tag-in-route/route.ts, a POST handler that calls updateTag("swiggy-menu") and nothing else. Call it and read the real response and server log.
Sample output (run for real against this course's harness):
$ curl -s -D - -X POST http://localhost:PORT/api/swiggy-menu/update-tag-in-route
HTTP/1.1 500 Internal Server Error
...
Server log:
⨯ Error: updateTag can only be called from within a Server Action. To invalidate cache tags in Route Handlers or other contexts, use revalidateTag instead. See more info here: https://nextjs.org/docs/app/api-reference/functions/updateTag
💡 Hint: This isn't a lint warning or a TypeScript type error — it's a real 500 at request time, with an error message that names the exact fix (revalidateTag) by name.
Exercise 4: The revalidateTag equivalent of updateTag, from a Route Handler
Scenario: Exercise 3 proved what Route Handlers can't do. Prove what they use instead for the same "no stale window" outcome.
What to do: Create app/api/swiggy-menu/reviews-expire/route.ts, calling revalidateTag("swiggy-reviews", { expire: 0 }) — the same tag swiggy-reviews/actions.ts invalidates with updateTag inside its Server Action.
Sample output (run for real against this course's harness):
$ curl -s -D - -X POST http://localhost:PORT/api/swiggy-menu/reviews-expire
HTTP/1.1 200 OK
content-type: application/json
💡 Hint: 200, not 500 — the only thing that changed between this and Exercise 3 is the function name. Same tag, same "no stale window" intent, but reached through the call Route Handlers are actually allowed to make.
Exercise 5: revalidatePath is scoped — prove a sibling route is untouched
Scenario: revalidateTag deliberately reaches across every route sharing a tag. Confirm revalidatePath does not do that — it only ever touches the one path you name.
What to do: Warm both /mandi/stats and /mandi/top-categories (two separately cached, unrelated routes). Call /api/mandi/revalidate-top-categories (section 2's own route) and measure both routes afterward.
Sample output (run for real against this course's harness):
$ curl -s -o /dev/null -w "stats:%{time_total}s\n" http://localhost:PORT/mandi/stats
stats:0.001053s
$ curl -s -o /dev/null -w "top-categories:%{time_total}s\n" http://localhost:PORT/mandi/top-categories
top-categories:0.000951s
$ curl -s -X POST http://localhost:PORT/api/mandi/revalidate-top-categories
{"revalidated":true,"path":"/mandi/top-categories"}
$ curl -s -o /dev/null -w "stats:%{time_total}s\n" http://localhost:PORT/mandi/stats
stats:0.001029s
$ curl -s -o /dev/null -w "top-categories:%{time_total}s\n" http://localhost:PORT/mandi/top-categories
top-categories:0.526104s
💡 Hint: /mandi/stats stays fast both times — revalidating /mandi/top-categories had zero effect on it. If these two routes shared a cacheTag and you'd called revalidateTag instead, both would have gone slow together on the next request. That contrast — path-scoped vs. tag-scoped — is the whole exercise.
Next
Part 12: Server Actions and forms
Show the solutions for Part 11 (5 files)
solutions/ex01.ts
// Solution to Exercise 1. Drop in as harness/app/api/mandi/revalidate-stats/route.ts.
// Delete afterward - not part of the harness's canonical Part 11 state.
import { revalidatePath } from "next/cache";
export async function POST() {
revalidatePath("/mandi/stats");
return Response.json({ revalidated: true, path: "/mandi/stats" });
}
// $ curl -s -o /dev/null -w "1st:%{time_total}s\n" http://localhost:PORT/mandi/stats
// 1st:0.009730s
// $ curl -s -o /dev/null -w "2nd:%{time_total}s\n" http://localhost:PORT/mandi/stats
// 2nd:0.001613s
// $ curl -s -X POST http://localhost:PORT/api/mandi/revalidate-stats
// {"revalidated":true,"path":"/mandi/stats"}
// $ curl -s -o /dev/null -w "after-revalidate:%{time_total}s\n" http://localhost:PORT/mandi/stats
// after-revalidate:0.665855s
// $ curl -s -o /dev/null -w "after-that:%{time_total}s\n" http://localhost:PORT/mandi/stats
// after-that:0.001895s
// Confirmed for real against this harness: revalidatePath works identically
// on a tagged route as it did on untagged /mandi/top-categories - it
// invalidates by path, the cacheTag is irrelevant to it.
solutions/ex02.ts
// Solution to Exercise 2. Drop in as harness/app/api/swiggy-menu/revalidate-ten/route.ts.
// Delete afterward.
import { revalidateTag } from "next/cache";
import { setPrice } from "@/app/swiggy-menu/lib/menu";
export async function POST(request: Request) {
const body = (await request.json()) as { id: string; price: number };
const updated = setPrice(body.id, body.price);
// A custom window, neither "max" nor { expire: 0 } - 10 real seconds of
// stale-serving before the next request blocks instead.
revalidateTag("swiggy-menu", { expire: 10 });
return Response.json({ revalidated: true, item: updated });
}
// $ curl -s -X POST http://localhost:PORT/api/swiggy-menu/revalidate-ten -d '{"id":"m1","price":55}'
// {"revalidated":true,"item":{"id":"m1","name":"Masala Dosa","price":55,"available":true}}
// $ curl -s http://localhost:PORT/swiggy-menu | grep -o '₹<!-- -->[0-9]*' # immediately after
// ₹90
// $ sleep 5
// $ curl -s http://localhost:PORT/swiggy-menu | grep -o '₹<!-- -->[0-9]*' # 5s later
// ₹55
// $ sleep 7
// $ time curl -s http://localhost:PORT/swiggy-menu | grep -o '₹<!-- -->[0-9]*' # 12s later
// real 0m0.545s
// Confirmed for real against this harness: the background refresh completed
// well before the 10s expire window ended (already 55 at the 5s mark), and
// the request past the 10s mark was genuinely slow (0.545s - the simulated
// read cost), confirming it blocked on a fresh recompute rather than
// serving a now-expired stale value.
solutions/ex03.md
# Solution to Exercise 3
Drop in as `harness/app/api/swiggy-menu/update-tag-in-route/route.ts`:
```ts
import { updateTag } from "next/cache";
export async function POST() {
updateTag("swiggy-menu");
return Response.json({ ok: true });
}
```
Real response and server log, captured against this harness:
```text
$ curl -s -D - -X POST http://localhost:PORT/api/swiggy-menu/update-tag-in-route
HTTP/1.1 500 Internal Server Error
vary: rsc, next-router-state-tree, next-router-prefetch, next-router-segment-prefetch
...
```
```text
⨯ Error: updateTag can only be called from within a Server Action. To invalidate cache tags in Route Handlers or other contexts, use revalidateTag instead. See more info here: https://nextjs.org/docs/app/api-reference/functions/updateTag
at r (.next/server/chunks/_0ciu9-s9ngdax._.js:1:97)
```
**Cleanup:**
```text
$ rm -rf app/api/swiggy-menu/update-tag-in-route
$ npx next typegen
$ npm run build
```
This is a real `500` thrown at **request time**, not a build-time or
TypeScript-level check — `updateTag` compiles fine inside a Route Handler,
and only fails the moment it's actually called, because the restriction is
about which *execution context* invoked it (a Server Action's own dispatch
mechanism vs. a plain Route Handler request), not something statically
checkable from the import alone. The error message names the exact fix
(`revalidateTag`) directly — see Exercise 4 for that fix applied to the same
tag.
solutions/ex04.ts
// Solution to Exercise 4. Drop in as harness/app/api/swiggy-menu/reviews-expire/route.ts.
// Delete afterward.
import { revalidateTag } from "next/cache";
export async function POST() {
// Contrast with updateTag's version (actions.ts, used inside the Server
// Action): this Route Handler cannot use updateTag at all (Exercise 3),
// so this is the correct way to get an immediate, no-stale-window
// invalidation of the SAME tag from outside a Server Action.
revalidateTag("swiggy-reviews", { expire: 0 });
return Response.json({ revalidated: true, tag: "swiggy-reviews", mode: "expire:0" });
}
// $ curl -s -D - -X POST http://localhost:PORT/api/swiggy-menu/reviews-expire
// HTTP/1.1 200 OK
// content-type: application/json
// Confirmed for real against this harness: 200, not 500 - the only change
// from Exercise 3's broken version is swapping updateTag for
// revalidateTag(tag, { expire: 0 }), which is exactly the function name
// Exercise 3's own error message pointed at.
solutions/ex05.md
# Solution to Exercise 5
No new file needed — this exercise reuses section 2's own
`app/api/mandi/revalidate-top-categories/route.ts` exactly as built, and
only adds a second route to the comparison.
**Steps, run for real against this harness:**
```text
$ curl -s -o /dev/null http://localhost:PORT/mandi/stats # warm
$ curl -s -o /dev/null http://localhost:PORT/mandi/top-categories # warm
$ curl -s -o /dev/null -w "stats:%{time_total}s\n" http://localhost:PORT/mandi/stats
stats:0.001053s
$ curl -s -o /dev/null -w "top-categories:%{time_total}s\n" http://localhost:PORT/mandi/top-categories
top-categories:0.000951s
$ curl -s -X POST http://localhost:PORT/api/mandi/revalidate-top-categories
{"revalidated":true,"path":"/mandi/top-categories"}
$ curl -s -o /dev/null -w "stats:%{time_total}s\n" http://localhost:PORT/mandi/stats
stats:0.001029s
$ curl -s -o /dev/null -w "top-categories:%{time_total}s\n" http://localhost:PORT/mandi/top-categories
top-categories:0.526104s
```
`/mandi/stats` stays fast in both measurements — calling `revalidatePath`
on `/mandi/top-categories` had precisely zero observable effect on it.
`/mandi/top-categories` itself goes from fast (cached) to slow (526ms,
matching its real 500ms simulated aggregation cost from Part 10, section 4)
immediately after the call, then would go fast again on the request after
that (not re-measured here, already proven in section 2).
This is the concrete difference between `revalidatePath` and
`revalidateTag`: a tag reaches every cache entry carrying it, across however
many unrelated routes happen to share that tag (the installed
`revalidatePath.md` reference's own worked example shows exactly this,
with a `/blog` page and a `/dashboard` page sharing a `'posts'` tag — calling
`revalidatePath('/blog')` leaves `/dashboard` serving stale data). A path is
scoped to exactly the one route named, and nothing else, no matter what
tags that route's own cached data happens to carry.
Common mistakes
| Mistake | Why it is wrong | Fix |
|---|---|---|
Expecting a request immediately after revalidateTag(tag, "max") to show fresh data |
The "max" profile is stale-while-revalidate by design — the next request still gets the old value, served fast, verified in section 3 | Use updateTag (Server Actions only) or revalidateTag(tag, { expire: 0 }) when the caller must see the change on the very next read |
| Assuming "stale-while-revalidate" means the origin server itself never blocks | Hitting the Next.js server directly (no CDN in front), the request that crosses the revalidate boundary pays the recompute cost synchronously — reproduced in section 3's going-deeper note |
Put a real CDN in front for true non-blocking background refreshes, or budget for an occasional slow request at the origin |
Calling updateTag from a Route Handler |
updateTag only works inside a Server Action — the installed docs are explicit, and this is exactly why api/swiggy-menu/revalidate/route.ts uses revalidateTag instead |
Use revalidateTag(tag, { expire: 0 }) outside a Server Action; reserve updateTag for inside one |
Porting export const revalidate = N or a single-argument revalidateTag(tag) from an older tutorial |
This harness's cacheComponents: true rejects the route segment config at build time, reproduced for real in section 6; the single-argument revalidateTag call is deprecated per the installed reference |
Use "use cache" + cacheLife() for the time-based half, and the two-argument revalidateTag(tag, profile) for the on-demand half |
Calling revalidatePath and expecting it to pre-compute the fresh page immediately |
It only marks the entry stale — the actual recomputation happens on the next visit, verified by the real ~500ms-slower request right after calling it in section 2 | If eager regeneration is the actual requirement, that's the Pages Router's res.revalidate(), not available in the App Router per the installed docs |
Quick recap
- Time-based revalidation (
cacheLife's own window, Part 10) and on-demand revalidation (revalidatePath/revalidateTag/updateTag, this part) are two named, distinct mechanisms in this install's own internals docs, not two names for the same thing. revalidatePathinvalidates by route path, no tag needed — verified with a real ~500ms-slower request immediately after calling it, and a fast one after that.revalidateTag(tag, "max")is stale-while-revalidate on demand: the request right after the call still gets the old value; a 1-second-later request gets the new one — both measured for real.revalidateTag(tag, { expire: 0 })blocks the very next request until fresh data is ready — no stale value is ever served.updateTagis Server-Action-only and folds the re-render into the action's own response (x-action-revalidated: 1, a real header) — the read-your-own-writes case, fully exercised in Part 12.export const revalidate = N(the pre-Cache-Components route segment config) is not just outdated — it's a build-time error undercacheComponents: true, reproduced for real, naming the exact incompatible config.
Checklist
- I called
revalidatePathfrom a Route Handler and measured the real timing difference on the request immediately after it, versus the one after that. - I called
revalidateTag(tag, "max")and proved — with two timed requests, not a guess — that the first still returns the stale value and a later one returns the fresh one. - I called
revalidateTag(tag, { expire: 0 })and proved the very next request blocks and returns fresh data directly, with no stale value in between. - I can state, from the installed docs' own wording, why
updateTagis restricted to Server Actions and whatrevalidateTagmust be used instead outside one. - I read a real
x-action-revalidatedresponse header and can explain what it confirms. - I reproduced the real build error from putting
export const revalidate = Ninside this harness, and can name the exact incompatible config from the error message.