Server Action with Form Validation
Next.js Server Action handling form submissions with validation, error messages, and redirect on success.
'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.
Type-Safe API Route Handler
Next.js App Router route handler with input validation, typed responses, and proper error handling.
Server Action with Revalidation
Mutate data with Server Actions and revalidate cached paths or tags for instant UI updates.
useFormValidation Hook
Lightweight form validation hook with field-level errors, touched tracking, and submit handling.
Authentication Middleware Guard
Next.js middleware that checks auth tokens on protected routes and redirects unauthenticated users to login.