On-Demand ISR: revalidateTag & Cache Tags Indexing
- Last updated
- Prerequisites:
- Next.js Data Cache
- Fetch API caching options
- nextjs
- isr
- caching
- revalidateTag
- data-cache
- app-router
Read at your depth
The practical view
`revalidateTag` allows you to purge specific entries from the Next.js Data Cache on demand. When fetching data, attach a tag: `fetch(url, { next: { tags: ['products'] } })`. When a mutation occurs (like in a Server Action), call `revalidateTag('products')`. The next time someone requests that data, Next.js refreshes it from the upstream source instead of serving stale cached data.
The same idea in other frameworks
Custom cache invalidation using TanStack Query `queryClient.invalidateQueries({ queryKey })`.Service-worker cache tagging or manual HTTP interceptor cache clearing.Nuxt `$fetch` cache invalidation via `clearNuxtData('key')`.SvelteKit `invalidate('app:products')` dependency tracking.Legacy vs modern
Time-based polling vs On-Demand Tag Revalidation
Time-based polling serves stale data or wastes compute; on-demand tag revalidation invalidates data immediately upon mutation.
fetch(url, { next: { revalidate: 3600 } }); // ❌ OLD: Stale for up to 1 hourrevalidateTag('products'); // ✅ NEW: Instant on-demand cache purgeInterview gotchas
Context
Interviewers want to see if you understand the scope of cache invalidation.
The mechanical answer
`revalidatePath` purges both the Full Route Cache and Data Cache for a specific URL path structure (including or excluding sub-routes). `revalidateTag` purges the underlying Data Cache entries across any page or component in the application that fetched data using that tag, without being bound to a single URL path.
Trap
`revalidatePath` can cause over-invalidation of unrelated data on a page, whereas `revalidateTag` surgically invalidates only the shared entity.
Context
This tests knowledge of server action lifecycle and read-your-own-writes semantics.
The mechanical answer
In Next.js, calling `revalidateTag` inside a Server Action marks the tag invalid. During the same server action response pass, Next.js re-renders the current route tree with the freshly fetched data so the client sees the updated state in one round-trip.
Trap
Calling `revalidateTag` in an external webhook handler invalidates the cache for *future* incoming requests, not for clients currently viewing the page without navigation.