Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Next.js ISR: Route Revalidate, revalidateTag, and On-Demand Invalidation

Two clocks and one trigger: route revalidate seconds, fetch-level tags, and a webhook that calls revalidateTag. A timer is a ceiling on freshness, never a guarantee.

~4 min readNext.js
#Next.js#ISR#Caching#Performance
3D illustration of cached page slabs with a countdown dial refreshing one and a webhook invalidating another

Quick Summary

Incremental Static Regeneration is the App Router's way of saying: serve a static render, then replace it later without rebuilding the whole site. There are two clocks and one trigger. The clocks are the route segment export const revalidate = <seconds> and the fetch-level { next: { revalidate: <seconds> } }; the trigger is on-demand invalidation through revalidatePath and revalidateTag.

The first visit after a page goes stale still gets the stale copy (stale-while-revalidate), and regeneration happens in the background. revalidate = 0 is not ISR — it forces dynamic rendering on every request. revalidate = false means cache forever, which is the default for a route with no dynamic APIs and no dynamic fetches.

On-demand revalidation is the part that matters in production. A CMS webhook that calls a route handler which runs revalidateTag("posts") updates every page that read that tag, without waiting for a timer and without a full deploy.

Basic Syntax & Core Signatures

ts
// app/blog/[slug]/page.tsx — route segment level export const revalidate = 3600; // seconds; false = infinite, 0 = dynamic export default async function Post({ params }: { params: Promise<{ slug: string }> }) { const { slug } = await params; const res = await fetch(`https://cms.example.com/posts/${slug}`, { next: { revalidate: 60, tags: ["posts", `post:${slug}`] }, }); const post = await res.json(); return <article>{post.body}</article>; }
ts
// app/api/revalidate/route.ts — on-demand trigger from a webhook import { revalidateTag, revalidatePath } from "next/cache"; import { NextRequest, NextResponse } from "next/server"; export async function POST(req: NextRequest) { const secret = req.headers.get("x-webhook-secret"); if (secret !== process.env.REVALIDATE_SECRET) { return NextResponse.json({ ok: false }, { status: 401 }); } const { tag, path } = await req.json(); if (tag) revalidateTag(tag); // invalidates every entry carrying that tag if (path) revalidatePath(path, "page"); // "page" | "layout" | undefined return NextResponse.json({ ok: true, revalidated: true, now: Date.now() }); }

revalidatePath takes the literal route path, not a URL with a query string. For dynamic segments pass the pattern and the type: revalidatePath("/blog/[slug]", "page") invalidates all pages of that route, while revalidatePath("/blog/hello") invalidates one. Tags are the safer default because they survive route restructuring: renaming /blog to /posts silently breaks a path-based webhook, not a tag-based one.

Timer resolution is not a promise of freshness. revalidate = 60 means "at most once per 60 seconds", and a page nobody visits is never regenerated at all. Never use a timer for correctness — use revalidateTag after a write.

Key Comparison Table

ControlWhere it is setGranularityEffect
export const revalidate = nRoute file (page.tsx, layout.tsx, route handler)Whole route outputRegenerates the rendered page after n seconds
fetch(..., { next: { revalidate: n } })Individual fetchOne data dependencyCaches that response for n seconds
fetch(..., { cache: "no-store" })Individual fetchOne fetchOpts the route out of static rendering
revalidateTag(t)Server function, route handler, Server ActionAll entries with that tagImmediate invalidation, no timer
revalidatePath(p, type)SameOne path or one route patternImmediate invalidation by URL
export const dynamic = "force-dynamic"Route segmentWhole routeNo full-route cache at all; per-request render
unstable_cache(fn, keys, { tags, revalidate })Wrapping a data functionFunction resultCaches non-fetch work such as a DB query

Practical Edge Cases & Deep Dives

1. generateStaticParams plus ISR for a large catalogue

generateStaticParams decides what is built at deploy time. With dynamicParams = true (the default) any slug not in the list renders on demand and is then cached like any other static page — this is the pattern for a 10,000-product catalogue where only the top 500 matter for cold start:

tsx
export const revalidate = 86400; export const dynamicParams = true; export async function generateStaticParams() { const top = await db.product.findMany({ orderBy: { views: "desc" }, take: 500 }); return top.map((p) => ({ slug: p.slug })); }

dynamicParams = false returns a 404 for every slug not prebuilt. That is the correct choice for a fixed set of pages, and a trap for a catalogue that grows after deploy.

2. Invalidating a tag written through unstable_cache

Data read from a database never passes through fetch, so it has no tags unless you add them. unstable_cache plus revalidateTag closes that gap; forgetting the tag means the webhook invalidates nothing and the page stays stale until the timer fires.

ts
import { unstable_cache } from "next/cache"; export const getPost = unstable_cache( async (slug: string) => db.post.findUnique({ where: { slug } }), ["post"], // key parts; arguments are appended { revalidate: 300, tags: ["posts"] }, );

In Next.js 15 the cacheTag / cacheLife APIs are the intended replacement; unstable_cache still works but is documented as legacy. Migrating means adding "use cache" to the function and calling cacheTag("posts") inside it.

3. Revalidating from a Server Action after a write

A Server Action that edits a record should invalidate before it returns, so the redirect that follows renders fresh output. Order matters: invalidate, then redirect. Calling redirect() first throws, and any revalidation after it never runs.

ts
"use server"; import { revalidateTag } from "next/cache"; import { redirect } from "next/navigation"; export async function updatePost(id: string, formData: FormData) { await db.post.update({ where: { id }, data: { title: String(formData.get("title")) } }); revalidateTag("posts"); revalidateTag(`post:${id}`); redirect(`/blog/${id}`); // must be last }

4. Stale CDN edge after revalidation

revalidatePath clears the Next.js cache; a CDN in front of the deployment can still hold its own copy according to its own TTL. On Vercel this is handled, but a self-hosted proxy or a Cloudflare rule with Cache-Control: s-maxage=3600 will keep serving the old page. The fix is to let Next.js own caching for HTML — do not add an independent HTML cache layer in front of a dynamic route — or to purge by URL/tag in the same webhook.

5. Build-time vs request-time revalidation of a route handler

A route handler is cached like a page when it only reads. If the webhook endpoint itself is cached, the second POST never reaches your code and looks like a silent no-op. Force it dynamic:

ts
// app/api/revalidate/route.ts export const dynamic = "force-dynamic"; export const runtime = "nodejs";

Also verify the method: a GET handler can be cached, a POST handler is not. A webhook configured to GET with a query secret will work once and then serve the cached response.

6. When ISR and cookies() collide

Calling cookies(), headers(), or searchParams in a page switches the route to dynamic rendering, and export const revalidate is ignored. The symptom is a page that never appears in the static build output and always shows x-vercel-cache: MISS. Keep the authenticated part in a client component or a separate dynamic route, and keep the cached shell free of request-time APIs.

Common Runtime & Configuration Mistakes

SymptomCauseFix
Page never updatesrevalidate set but no traffic, or webhook cachedAccept timer semantics, or call revalidateTag; mark the webhook force-dynamic
revalidatePath does nothingPath does not match the rendered route (locale prefix, group)Use the URL path as rendered, or switch to tags
First render after invalidation still staleCDN or client router cache layerrouter.refresh() on the client, purge the proxy on the server
Route became dynamic unexpectedlycookies(), headers(), or searchParams read in the pageMove them to a dynamic segment or a client component
fetch cache ignoredcache: "no-store" elsewhere in the same routeOne no-store fetch makes the whole route dynamic
Stale data in a Server Component after actionrevalidate missing on the fetch and no tagAdd tags at the fetch and invalidate that tag in the action

Try matching browser tools

All tools

Small utilities that fit Next.js work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Next.js guides

More in Next.js

All Next.js guides

The guides filed next to this one in Next.js, in library order.