Revalidating Data
Explicitly invalidate cached data on demand using revalidatePath and revalidateTag.
Time-Based vs On-Demand Revalidation
The revalidate option covered in the previous lesson is time-based — it refreshes data after an interval elapses. On-demand revalidation is different: it lets your own code say "this specific data just changed, invalidate it right now," typically right after a create, update, or delete.
revalidatePath
revalidatePath(path) clears the cached data and rendered output for a specific route, so the next visit regenerates it fresh.
'use server';import { revalidatePath } from 'next/cache';
export async function createPost(formData) { await db.post.create({ data: { title: formData.get('title') } }); revalidatePath('/blog'); // /blog will show the new post on next visit}revalidateTag
revalidateTag(tag) invalidates every cached fetch call that was tagged with that name, regardless of which route it lives on — useful when the same data appears in multiple places.
// Fetching with a tagconst res = await fetch('https://api.example.com/posts', { next: { tags: ['posts'] },});'use server';import { revalidateTag } from 'next/cache';
export async function deletePost(id) { await db.post.delete({ where: { id } }); revalidateTag('posts'); // invalidates every fetch tagged "posts", anywhere}Reach for revalidatePath when the change affects one specific page. Reach for revalidateTag when the same data appears across several different routes — like a "posts" list shown on both a homepage and a blog index.
A Typical Mutation Flow
FAQs
Inside Server Actions and Route Handlers — they are server-only functions and won't work inside a Client Component or plain Server Component render.
Yes when combined with Server Actions correctly — the page reflects the change right after the action completes, without a manual refresh.
Summary
On-demand revalidation lets a mutation immediately invalidate exactly the cached data it affects. Next, you'll learn how to build your own API endpoints in Next.js using Route Handlers.