typescriptbeginner
Redirect After Server Action
Use redirect() inside a server action to navigate after form submission in Next.js App Router.
typescriptPress ⌘/Ctrl + Shift + C to copy
'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.
typescriptintermediate
Server Action with Form Validation
Next.js Server Action handling form submissions with validation, error messages, and redirect on success.
Best for: Blog post creation
#server-actions#forms
typescriptintermediate
Next.js Server Actions with Forms
Use Server Actions for form handling with validation, optimistic updates, and error handling.
Best for: Form submissions without API routes
#nextjs#server-actions
typescriptadvanced
Form with Server Action Validation
Build forms using Next.js server actions with server-side validation, error handling, and useActionState.
Best for: Contact form submissions
#nextjs#forms
typescriptbeginner
useFormStatus for Pending UI States
Use useFormStatus hook to show loading states during server action form submissions.
Best for: form submission UX
#nextjs#forms