On-Demand Cache Revalidation with revalidatePath and revalidateTag
On-Demand Cache Revalidation with revalidatePath and revalidateTag
Static caching delivers blazing speed, but modern web applications require instant updates when content changes. Next.js provides two fundamental on-demand revalidation APIs: revalidatePath (invalidating specific route URLs) and revalidateTag (invalidating data associated with semantic cache tags across the entire application).
1. Path-Based Revalidation: revalidatePath()
revalidatePath allows purging cached data and server-rendered HTML for a specific route:
2. Tag-Based Revalidation: revalidateTag() (Semantic Granularity)
While revalidatePath targets a URL, a single piece of data (e.g. a course's title and price) might be displayed on multiple pages: the Homepage, the Course Catalog, the Checkout Page, and the User Dashboard.
Revalidating paths one-by-one is fragile. revalidateTag associates data with a tag, purging every occurrence across all pages in a single call!
3. Comparison: When to Use Which?
| Feature | revalidatePath | revalidateTag |
|---|---|---|
| Scope | Targets a specific URL path or route layout | Targets semantic data entities across the entire site |
| Use Case | Form submission updating a single specific view | CMS webhooks, product price updates, user profile edits |
| Granularity | Coarse-grained (entire page or layout) | Fine-grained (exact data payload) |
Multiple Choice Questions
revalidatePath('/blog') do?revalidatePath and revalidateTag be executed?'layout' as the second argument to revalidatePath('/dashboard', 'layout') accomplish?Optimistic UI Updates with React useOptimistic Hook
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.