typescriptintermediate
Server Action with Form Validation
Next.js Server Action handling form submissions with validation, error messages, and redirect on success.
typescriptPress ⌘/Ctrl + Shift + C to copy
'use server';
import { redirect } from 'next/navigation';
interface FormState {
errors: Record<string, string>;
message?: string;
}
export async function createPost(
_prevState: FormState,
formData: FormData
): Promise<FormState> {
const title = formData.get('title') as string;
const content = formData.get('content') as string;
const errors: Record<string, string> = {};
if (!title || title.length < 3) {
errors.title = 'Title must be at least 3 characters';
}
if (!content || content.length < 10) {
errors.content = 'Content must be at least 10 characters';
}
if (Object.keys(errors).length > 0) {
return { errors };
}
// Replace with your database call
const post = { id: crypto.randomUUID(), title, content };
console.log('Created:', post);
redirect(`/posts/${post.id}`);
}
// Client component usage:
// 'use client';
// import { useActionState } from 'react';
// import { createPost } from './actions';
//
// const [state, action, pending] = useActionState(createPost, { errors: {} });
// <form action={action}>
// <input name="title" />
// {state.errors.title && <p>{state.errors.title}</p>}
// <textarea name="content" />
// <button disabled={pending}>Submit</button>
// </form>Use Cases
- Blog post creation
- Contact forms
- User profile updates
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
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
typescriptintermediate
Server Action Validation with Zod
Validate form data in server actions using Zod schemas with type-safe error handling.
Best for: contact forms
#nextjs#zod
typescriptintermediate
File Upload with Server Action
Handle file uploads using server actions with validation, size limits, and storage.
Best for: image uploads
#nextjs#file-upload