Learn the concept
Server Actions
Server Actions are async functions that execute on the server, marked with 'use server'. They enable secure data mutations directly from components without creating API routes, support progressive enhancement (forms work without JavaScript), and integrate seamlessly with React's form handling and optimistic updates.
Server Actions are async functions that run exclusively on the server. They:
POST /api/submit - call functions directlyuseActionState (from react), useFormStatus (from react-dom), and useOptimistic// Option 1: 'use server' at top of file (all exports are actions)
'use server';
export async function createPost(formData: FormData) { ... }
// Option 2: Inline in Server Component
async function Page() {
async function handleSubmit(formData: FormData) {
'use server';
// This runs on server
}
}<form action={...}>FormData parameterrevalidatePath() to refresh cached pagesrevalidateTag() for fine-grained cache controluseOptimistic for instant UI feedbackuseFormStatus for loading states// app/actions.ts
'use server';
import { revalidatePath } from 'next/cache';
import { redirect } from 'next/navigation';
import { z } from 'zod';
const PostSchema = z.object({
title: z.string().min(1, 'Title is required').max(100),
content: z.string().min(10, 'Content must be at least 10 characters'),
});
export async function createPost(prevState: any, formData: FormData) {
// Validate input
const validatedFields = PostSchema.safeParse({
title: formData.get('title'),
content: formData.get('content'),
});
if (!validatedFields.success) {
return {
errors: validatedFields.error.flatten().fieldErrors,
message: 'Invalid fields. Failed to create post.',
};
}
// Insert into database
try {
await db.post.create({ data: validatedFields.data });
} catch (error) {
return { message: 'Database error: Failed to create post.' };
}
// Revalidate and redirect
revalidatePath('/posts');
redirect('/posts');
}Building checkout forms that work without JavaScript using Server Actions with form action, then enhancing with optimistic updates
Calling Prisma/Drizzle directly in Server Actions for CRUD operations without creating separate API endpoints
Using Server Actions with FormData to handle file uploads, process them server-side, and update the UI optimistically
Build a task manager with create, read, update, delete using Server Actions, Zod validation, and optimistic updates
Build a contact form that works with JS disabled, then enhance with useActionState for validation and useFormStatus for loading