Revalidating after a mutation
A mutation changes data, but the page the user sees may still come from Next.js's
cache. After writing, tell Next.js which cached data is now stale by calling
revalidatePath or revalidateTag from next/cache inside the Server
Function.
// app/actions.ts
'use server';
import { revalidatePath, revalidateTag } from 'next/cache';
export async function createPost(formData: FormData) {
await db.post.create({ data: { title: formData.get('title') } });
revalidatePath('/posts');
}
revalidatePath('/posts') marks that URL's cached output as stale, so the next
visit re-renders it with fresh data. revalidateTag('posts') does the same for
every cached entry tagged with cacheTag('posts'), which is often the better
choice when the same data appears on several routes.
The call belongs in the action, not in the component that renders the data:
rendering must stay free of side effects. Revalidate after the write
succeeds, so the refreshed UI reflects the mutation, and before you
redirect (see the next Lesson) so the destination shows the new state.
You are about to answer a short quiz on revalidatePath / revalidateTag.