Advertisement
Advanced Next.js, Caching

How would you manually clear cached data after a user performs an action, such as creating a new post?

Short answer

You call the revalidatePath or revalidateTag function inside a server action or route handler after the update completes, telling Next.js to throw away the old cached version of a specific page or tagged data so the next request fetches fresh information immediately.

Save Next.js mock interview
Advertisement
AModel answer
You call the revalidatePath or revalidateTag function inside a server action or route handler after the update completes, telling Next.js to throw away the old cached version of a specific page or tagged data so the next request fetches fresh information immediately.
'use server';
import { revalidatePath } from 'next/cache';

export async function createPost(formData) {
  await savePost(formData);
  revalidatePath('/blog');
}
Real-world example
A blog admin panel clears the cache for the blog listing page immediately after a new post is published, so readers see the new post right away instead of waiting for the next scheduled revalidation.
Likely follow-ups
  • What is the difference between revalidatePath and revalidateTag?
  • Can you revalidate multiple related pages at the same time?
Related topics