Nextjs Fundamentals · Server Functions & Mutations

Redirecting after a mutation

redirect

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.

  1. redirect is imported from ___.
  2. redirect throws a control-flow exception, so code after it does not run.
  3. You should call revalidatePath after redirect so the destination is fresh.
  4. Wrapping redirect in a try/catch that swallows the exception prevents the navigation.
  5. Call redirect from inside the Server ___.