Skip to content
next.js questions

Next.js · 6 of 10middle~1 min

What is the difference between revalidateTag, updateTag and revalidatePath?

#caching

Revalidation

Cached data is refreshed either by time (cacheLife) or on demand after a mutation. For on-demand revalidation there are three functions:

updateTagrevalidateTagrevalidatePath
TargetEntries with a tagEntries with a tagEverything on a route
BehaviorExpires immediatelyStale-while-revalidateInvalidates the path
WhereServer Actions onlyServer Actions, Route HandlersServer Actions, Route Handlers
Use caseUser must see their own changeBackground refresh, a small delay is fineNo tags known for the route

Example

ts
'use server'; import { updateTag } from 'next/cache'; export async function addComment(postId: string, text: string) { await db.comment.create({ data: { postId, text } }); updateTag(`post-${postId}`); // the author sees the comment right away }
ts
// app/api/cms-webhook/route.ts import { revalidateTag } from 'next/cache'; export async function POST() { revalidateTag('posts', 'max'); // serve stale content while fresh content is generated return Response.json({ ok: true }); }

Tips

  • Prefer tags over paths: they are precise and don't invalidate unrelated data.
  • For content from a CMS use a long cacheLife('max') + cacheTag and call revalidateTag from a webhook instead of polling by time.
  • router.refresh() only refetches the current route on the client, it does not clear the server cache.

updated

did you know it?

related questions