On-demand revalidation lets you invalidate cached/static pages exactly when data changes — rather than waiting for a time-based interval. It's the precise complement to time-based ISR (revalidate: N).
Time-based vs on-demand
revalidate = ;
On-demand revalidation lets you invalidate cached/static pages exactly when data changes — rather than waiting for a time-based interval. It's the precise complement to time-based ISR (revalidate: N).
revalidate = ;
Time-based ISR is simple but imperfect: too short = unnecessary regeneration; too long = stale content. On-demand fixes this by triggering revalidation from your own code when a change actually happens.
import { revalidatePath, revalidateTag } from "next/cache";
// 1. Tag your fetches, then invalidate by tag
await fetch("https://api/posts", { next: { tags: ["posts"] } });
revalidateTag("posts"); // refresh EVERY page/fetch tagged "posts"
// 2. Or invalidate a specific path
revalidatePath("/blog/my-post");
// app/api/revalidate/route.ts — called by your CMS when an editor publishes
import { revalidateTag } from "next/cache";
import { NextRequest, NextResponse } from "next/server";
export async function POST(req: NextRequest) {
const secret = req.nextUrl.searchParams.get("secret");
if (secret !== process.env.REVALIDATE_SECRET) { // verify it's really your CMS
return NextResponse.json({ ok: false }, { status: 401 });
}
revalidateTag("posts"); // rebuild affected pages now
return NextResponse.json({ revalidated: true });
}
The flow: editor publishes in the CMS → CMS calls your webhook → revalidateTag("posts") invalidates the cache → the next visitor gets freshly regenerated static HTML. Pages stay static-fast and update immediately on publish.
"use server";
export async function createPost(data) {
await db.post.create({ data });
revalidateTag("posts"); // user sees their new post immediately
}
On-demand revalidation gives you the holy grail: static performance with real-time freshness.
Instead of guessing a revalidation interval, you invalidate precisely when content changes — via webhooks (CMS publish) or after Server Action mutations — using revalidateTag/revalidatePath.
It eliminates both stale content and wasteful over-regeneration, making ISR practical for content that updates unpredictably.