On-Demand Revalidation (revalidateTag)
Purge cache entries across multiple routes simultaneously using tags.
Tag-Based Caching
revalidateTag is a powerful Next.js utility that allows you to purge data from the cache based on custom strings (tags) instead of URL paths.
You attach these tags to your fetch requests, grouping related data together regardless of what page it lives on.
The Multi-Route Problem
Imagine an e-commerce site where a product's price is displayed on the Homepage, the Category page, and the Product Details page.
If you change the price, using revalidatePath would require you to manually list every single URL where that product appears. With revalidateTag, you just tag those fetches with 'prices', and a single revalidateTag('prices') call purges all of them instantly across the entire application.
Tagging and Purging
Step 1: Tag your fetch request: fetch('https://api.store.com/shoes', { next: { tags: ['shoes', 'catalog'] } }).
Step 2: After updating a shoe in the database, call revalidateTag('shoes') inside your Server Action. Every cache entry across the app containing that tag is immediately flushed.
The Tag Network
Interact with the Server Action below. Notice how calling revalidateTag('products') instantly identifies and purges the cached data across completely different URL routes simultaneously.
Server Action
export async function updateData() {
await db.record.update(data);
await revalidateTag('products');
Cached Routes & Their Fetch Tags
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
revalidateTagclears data based on custom tags, not URLs.- Add tags via
fetch(url, { next: { tags: ['my-tag'] } }). - A single
revalidateTagcall can purge data across multiple pages simultaneously. - Tags must match exactly; typos will silently fail to clear the cache.
- Always use a constants file for your tag names to prevent typos.
Done with this concept?
Mark it complete to track your progress. No login needed.