Nextjs Fundamentals · Server Functions & Mutations

Revalidating after a mutation

revalidatePath / revalidateTag

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.

  1. revalidatePath and revalidateTag are imported from ___.
  2. After a mutation, you should revalidate so the UI reflects the change.
  3. You should call revalidatePath during a component's render.
  4. revalidateTag invalidates every cached entry tagged with ___.
  5. Revalidation should happen after the write succeeds.