Redirecting after a mutation
After a successful mutation you often want to move the user to another page —
back to a list, or to the item they just created. Call redirect from
next/navigation inside the Server Function:
// app/actions.ts
'use server';
import { revalidatePath } from 'next/cache';
import { redirect } from 'next/navigation';
export async function createPost(formData: FormData) {
await db.post.create({ data: { title: formData.get('title') } });
revalidatePath('/posts');
redirect('/posts');
}
redirect works by throwing a special control-flow exception that Next.js
catches and turns into a navigation. That has two consequences. First, any code
written after redirect never runs, so put revalidatePath (or
revalidateTag) before it. Second, do not call redirect inside a
try/catch that would swallow the thrown exception — the navigation would be
cancelled.
The redirect happens on the server, so the browser is sent straight to the destination with fresh data rather than re-rendering the page it was on.
You are about to answer a short quiz on redirect.