snippettypescriptnextjsModeratependingCanonical
React Server Actions -- Next.js form handling pattern
Viewed 0 times
Next.js 14+
Server Actionsuse serveruseFormStateuseFormStatusprogressive enhancement
nodejsbrowser
Problem
Handling form submissions in Next.js App Router requires API routes, client-side fetch, loading states, and error handling.
Solution
Use React Server Actions with useFormState/useFormStatus for progressive enhancement.
Code Snippets
Server Action with validation
'use server';
import { revalidatePath } from 'next/cache';
export async function createPost(prevState: any, formData: FormData) {
const title = formData.get('title') as string;
if (!title || title.length < 3) {
return { error: 'Title must be at least 3 characters' };
}
await db.insert(posts).values({ title });
revalidatePath('/posts');
return { success: true };
}Revisions (0)
No revisions yet.