Next.jsMedium

What is revalidatePath and revalidateTag?

Both invalidate cached data on demand. revalidatePath(path, type?) invalidates everything cached for a URL path. revalidateTag(tag, profile) invalidates every cache entry with a given tag, wherever it is used, using stale-while-revalidate. In Next.js 16, revalidateTag requires the second cacheLife profile argument, and updateTag was added for immediate expiry.

revalidateTag(tag, profile)

  • Tags come from cacheTag() inside "use cache" or fetch(url, { next: { tags } }).
  • Stale-while-revalidate: the next visitor may get the stale version once while fresh content is generated in the background.
  • The profile controls how long stale content can be served: 'max' (recommended), 'hours', 'days', a custom profile, or { expire: seconds }.
  • The one-argument form is deprecated and is a TypeScript error.
  • Callable from Server Functions and Route Handlers (webhooks).

updateTag(tag)

  • Immediately expires the tag; the next read waits for fresh data.
  • Server Functions only. Use it when the user must see their own change right away.

revalidatePath(path, type?)

  • Invalidates data and output for a specific path: revalidatePath("/blog/hello").
  • For dynamic segments, pass the route pattern with a type: revalidatePath("/blog/[slug]", "page") or revalidatePath("/dashboard", "layout") (includes nested routes).
  • revalidatePath("/", "layout") invalidates everything.
  • Less precise; prefer tags.

Client effect

Called from a Server Function, any of these also clears the client router cache in the same response, so the UI updates immediately.

Pages Router

res.revalidate("/path") in an API route.

Code example

tsx
1// app/api/cms-webhook/route.ts
2import { revalidateTag, revalidatePath } from "next/cache";
3
4export async function POST(req: Request) {
5 if (req.headers.get("x-secret") !== process.env.CMS_SECRET) return new Response(null, { status: 401 });
6 const { type, slug } = await req.json();
7
8 if (type === "post") revalidateTag(`post:${slug}`, "max"); // background refresh
9 if (type === "menu") revalidatePath("/", "layout"); // everything under the root layout
10 return Response.json({ ok: true });
11}
12
13// app/posts/actions.ts
14// "use server";
15// import { updateTag } from "next/cache";
16// export async function rename(slug: string, title: string) {
17// await db.post.update({ where: { slug }, data: { title } });
18// updateTag(`post:${slug}`); // author sees the new title immediately
19// }

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.

Open in study app