Next.js 38: Revalidating After a Mutation
easy⏱ 5 mincoursenextjs
Telling Next.js the cache is stale
Next.js caches rendered routes and fetch() calls aggressively. After a mutation, call revalidatePath('/posts/1') to purge the cache for that specific route, or revalidateTag('comments') to purge every cached fetch tagged 'comments', however many routes that touches. Either call at the end of a Server Action makes the next render — often the very form you just submitted — reflect the new data immediately.
'use server';
import { revalidatePath } from 'next/cache';
export async function addComment(postId: string, formData: FormData) {
const text = formData.get('comment');
await db.comment.create({ data: { postId, text } });
revalidatePath(`/posts/${postId}`); // this page re-fetches fresh data next render
}
revalidatePath vs revalidateTag
Reach for revalidatePath when the mutation only affects one known route. Reach for revalidateTag when several different routes cache the same underlying data (tag every related fetch with { next: { tags: ['comments'] } }) — one revalidateTag('comments') call invalidates all of them at once, wherever they're rendered.
No manual refetch or reload needed
Before Server Actions, keeping the UI in sync after a mutation meant either a full page reload (window.location.reload() — slow, loses scroll position) or hand-rolled client state syncing. Revalidation replaces both: the framework refetches only what's marked stale, and React reconciles the update efficiently.
Ship the full comment feature
Combine everything: validate name and comment server-side and show inline errors; show the new comment optimistically the instant it's submitted (pending style); disable the form while the action runs; and once it 'succeeds', simulate revalidatePath by re-reading the canonical comment list from your fake data store so the UI shows exactly what the 'server' now has. Keep export default App.