Next.js Course
Next.js
/
Advanced

revalidateTag()

Definition

A utility function that purges cached data across multiple different URLs simultaneously based on a custom string label (tag).

Explain Like I'm New

If you update a Product's price, that price might be displayed on the `/home` page, the `/shop` page, and the `/product/123` page. Calling `revalidatePath` three times is annoying. Instead, you tag all those fetches with `'pricing'`. When the price changes, you just call `revalidateTag('pricing')` and it updates the price everywhere instantly.

Real World Example

A headless CMS webhook. When an editor publishes an article, the CMS pings your API. Your API runs `revalidateTag('articles')`, instantly updating every page on your site that displays articles.

Common Use Cases

  • •Complex cache architectures
  • •Global data updates
  • •CMS Webhooks

Interactive Example

// 1. The Fetching Side (Happening on multiple different pages)
export async function getProducts() {
  // We tag this specific request with the label 'catalog'
  const res = await fetch('https://api.store.com/products', {
    next: { tags: ['catalog'] }
  });
  return res.json();
}

// 2. The Mutation Side (Inside a Server Action or API Route)
import { revalidateTag } from 'next/cache';

export async function restockInventory() {
  'use server';
  await db.updateInventory();
  
  // BOOM! Every fetch request anywhere in the app tagged with 'catalog' 
  // is instantly purged and refetched.
  revalidateTag('catalog');
}

Interview Questions

basic

  • Where do you assign a tag to a specific fetch request?

intermediate

  • What is the primary advantage of `revalidateTag` over `revalidatePath`?

Flash Cards

Question

Where to assign?

Click to reveal answer
Answer

Inside the fetch options object: `fetch('url', { next: { tags: ['my-tag'] } })`.

Question

Primary advantage?

Click to reveal answer
Answer

`revalidatePath` is tied to URLs. If a piece of data exists on 15 different URLs, updating it is a nightmare. `revalidateTag` is tied to the DATA itself, allowing you to update it globally across the entire app with one function call.