How do I revalidate cached data after a mutation in Next.js App Router?

asked 3 months ago364 viewsen

5

I have a Server Component that lists posts, and a Server Action that creates a post. After creating, the list doesn't show the new post until I hard-refresh.

Environment:Next.js 15

AI diagnosis

AI-generated. Not an answer — the community below confirms or corrects it. Always verify before relying on it.

asked 3 months ago

1 Answer

5
✓
✓ Accepted answer

Call revalidatePath (or revalidateTag) inside the Server Action after the write:

'use server';
import { revalidatePath } from 'next/cache';

export async function createPost(formData: FormData) {
  await db.post.create({ data: { title: String(formData.get('title')) } });
  revalidatePath('/posts');
}

When a Server Action revalidates, Next.js sends the fresh RSC payload back in the same response, so the list updates without a reload.

For data used on many pages, tag your fetches (fetch(url, { next: { tags: ['posts'] } }) or unstable_cache(..., { tags: ['posts'] })) and call revalidateTag('posts').

Sign in to tell others whether this worked.

answered 3 months ago

Sign in and verify your email to post an answer.