Next.jsMedium
What is on-demand revalidation?
On-demand revalidation refreshes cached data as soon as it changes, instead of waiting for a timer. You tag cached data, then call revalidateTag, updateTag or revalidatePath from a Server Function or Route Handler, typically after a mutation or a CMS webhook.
The APIs (Next.js 16)
revalidateTag(tag, profile): marks tagged entries stale with stale-while-revalidate. Visitors get the old content once while fresh content is generated. The second argument is now required;'max'is recommended. Works in Server Functions and Route Handlers. Best for content where a short delay is fine.updateTag(tag): immediately expires the entries so the next read waits for fresh data. Server Functions only. Use it for read-your-own-writes, so a user sees their change instantly.revalidatePath(path, type?): invalidates everything for a path ('page'or'layout'). Less precise; prefer tags.refresh(): refreshes the client router from a Server Function without touching cached data.
Calling these from a Server Function also clears the browser's client cache, so the UI updates on the response.
Tagging data
- Cache Components:
cacheTag('posts')inside"use cache". fetch(url, { next: { tags: ['posts'] } })(previous model).
Webhook pattern
A CMS calls /api/revalidate with a secret. The Route Handler checks the secret and calls revalidateTag('post:slug', 'max').
Pages Router
await res.revalidate('/blog/my-post') inside an API route.
Code example
tsx
1// app/api/revalidate/route.ts - CMS webhook2import { revalidateTag } from "next/cache";3import type { NextRequest } from "next/server";45export async function POST(request: NextRequest) {6 if (request.headers.get("x-webhook-secret") !== process.env.CMS_WEBHOOK_SECRET) {7 return Response.json({ error: "Unauthorized" }, { status: 401 });8 }9 const { slug } = await request.json();10 revalidateTag(`post:${slug}`, "max"); // serve stale once, refresh in background11 return Response.json({ revalidated: true });12}1314// app/posts/actions.ts - user edits their own post15// "use server";16// import { updateTag } from "next/cache";17// export async function savePost(formData: FormData) {18// await db.post.update({ ... });19// updateTag(`post:${formData.get("slug")}`); // user sees the change immediately20// }
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the Next.js set.