Next.js
6. Revalidate - Time-Based and On-Demand
Time-based revalidation (`revalidate: N`) refreshes data automatically on a schedule but introduces unnecessary latency. `revalidatePath` and `revalidateTag` allow you to proactively trigger cache invalidation immediately when mutations occur, without waiting for the cache timer to expire.
On this page
With the { next: { revalidate: 3600 } } pattern covered previously, data only refreshes after the exact predefined interval elapses, even if a triggering event (such as an admin publishing a new post) occurs much earlier. On-demand revalidation eliminates this unnecessary lag.
1. The limitation of time-based revalidation
- Example: an article feed page uses
revalidate: 3600(1 hour). An admin publishes a new article, yet that post will take up to an hour to show up, even though the exact moment requiring cache invalidation (immediately post-publish) is precisely known.
2. revalidatePath: instantly revalidating a specific URL path
ts
'use server';
import { revalidatePath } from 'next/cache';
async function createPost(data) {
await db.post.create({ data });
revalidatePath('/blog'); // the next request to /blog receives fresh data immediately
}
- Used when you know the exact single path that needs invalidation.
3. revalidateTag: bulk revalidating multiple targets with a single call
- The issue: if a new post appears across several distinct pages (
/blog,/,/authors/[id]), usingrevalidatePathrequires invoking it individually for each route, making it easy to miss locations. - Solution: attach
tagstofetch()calls across all related contexts, even if the underlying API endpoints differ:
tsx
const posts = await fetch('[https://api.example.com/posts](https://api.example.com/posts)', {
next: { tags: ['posts'] }
});
- A single function call prompts Next.js to locate and purge every cached payload tagged with that key, without needing an exhaustive list of individual paths:
ts
revalidateTag('posts');
4. When to choose which
revalidatePath: you know the exact, isolated URL path that requires purging.revalidateTag: the same data entity is shared across multiple disjointed views, making an exhaustive list of paths impractical or fragile.- Both are typically executed within Server Actions or Route Handlers, immediately following successful write operations (create/update/delete).
