Lesson 17 +10 XP

On-Demand & Time-Based Revalidation (revalidatePath, revalidateTag)

On-Demand & Time-Based Revalidation (revalidatePath, revalidateTag)

While time-based revalidation clears caches automatically after a fixed time duration, On-Demand Revalidation allows invalidating cached data immediately when events occur (such as a database edit or a CMS webhook).

1. Tag-Based Revalidation (revalidateTag)

Tag-based revalidation allows labeling one or more fetch calls with a string tag, then purging all responses matching that tag with a single function call.

Tagging Data Requests:

// app/products/page.tsx
export default async function ProductsPage() {
  const res = await fetch('https://api.example.com/products', {
    next: { tags: ['products', 'inventory'] },
  });
  const products = await res.json();

  return <div>{/* Product List */}</div>;
}

Purging Tagged Cache On-Demand:

Call revalidateTag() inside a Server Action or Route Handler:

// app/actions.ts
'use server';

import { revalidateTag } from 'next/cache';

export async function updateProductStock(productId: string) {
  await db.product.update({ where: { id: productId }, data: { stock: 0 } });

  // Instantly purge all cached fetch requests tagged with 'products'!
  revalidateTag('products');
}

2. Path-Based Revalidation (revalidatePath)

revalidatePath() purges cached data and pre-rendered static HTML for a specific URL path segment:

'use server';

import { revalidatePath } from 'next/cache';

export async function createBlogPost(formData: FormData) {
  await db.post.create({
    data: { title: formData.get('title') as string },
  });

  // Purge the static cache for the /blog page!
  revalidatePath('/blog');
  
  // Or purge all sub-routes matching a layout:
  revalidatePath('/blog/[slug]', 'page');
}

Revalidation Methods Compared

FunctionImport SourceScopeUse Case
revalidateTag(tag)next/cachePurges all fetch calls tagged with tag across all routesBroad data invalidation (e.g., e-commerce stock)
revalidatePath(path)next/cachePurges static HTML and fetch cache for a specific pathSpecific page invalidation (e.g., blog post list)

TL;DR

  • Tag fetch requests using { next: { tags: ['my-tag'] } }.
  • Invalidate tagged fetch responses across the entire application using revalidateTag('my-tag').
  • Invalidate static page HTML and caches for a specific URL path using revalidatePath('/path').
  • Call revalidation helpers inside Server Actions or API Route Handlers.