Topic 33 of 39
Cache Revalidation
Overview
Revalidation is the process of purging cached data and fetching fresh data. Next.js supports Time-based Revalidation (ISR) and On-Demand Revalidation (via paths or tags).
Syntax
tsx
// 1. Time-based (Revalidate every hour)
fetch('https://api.com', { next: { revalidate: 3600 } });
// 2. Tag-based (Mark fetch with a tag)
fetch('https://api.com', { next: { tags: ['blog-posts'] } });
// 3. On-Demand Revalidation (Inside a Server Action)
import { revalidateTag, revalidatePath } from 'next/cache';
export async function createPost() {
await db.create();
revalidateTag('blog-posts'); // clears specific fetch caches
revalidatePath('/blog'); // clears route cache
}Common Pitfalls
- Using
revalidatePathbut wondering why layout data didn't update (you must specify the exact path or use layout type revalidation). - Setting
revalidate: 0instead ofcache: 'no-store'. They do the same thing, but 'no-store' is more semantic.
Interview Questions
Q:
What is the difference between
revalidatePath and revalidateTag?A:
revalidatePath clears the cache for a specific URL route. revalidateTag clears the cache for any fetch requests across the entire app that were marked with that specific tag.
Real-World Example
Updating an e-commerce product price and instantly clearing the cache for that specific product.
example
tsx
export async function updatePrice(id: string, newPrice: number) {
'use server';
await db.updatePrice(id, newPrice);
revalidateTag(`product-${id}`); // Instantly updates cached fetches for this product
}Check Your Knowledge
Test your understanding of Cache Revalidation with these quick questions.