typescriptbeginner

Redirect After Server Action

Use redirect() inside a server action to navigate after form submission in Next.js App Router.

typescript
'use server';

import { redirect } from 'next/navigation';
import { revalidatePath } from 'next/cache';

export async function createPost(formData: FormData) {
  const title = formData.get('title') as string;
  const content = formData.get('content') as string;

  if (!title || !content) {
    throw new Error('Title and content are required');
  }

  const post = await db.post.create({
    data: { title, content },
  });

  revalidatePath('/posts');
  redirect(`/posts/${post.id}`);
}

Use Cases

  • form submissions
  • post-action navigation
  • CRUD operations

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.