Loading lessons...
Introduction to Server Actions ('use server')
Introduction to Server Actions ('use server')
Server Actions are asynchronous functions that execute on the server. They allow handling form submissions, data mutations, and backend logic directly from React components without building dedicated API endpoints.
Defining Server Actions
You can declare Server Actions in two places:
- Inside a dedicated file: Add
'use server';at the top of the module file. All exported functions become Server Actions. - Inline inside a Server Component: Add
'use server';at the top of the function body.
Dedicated Action File (Recommended):
// app/actions.ts
'use server';
import db from '@/lib/db';
import { revalidatePath } from 'next/cache';
export async function createTodo(formData: FormData) {
const title = formData.get('title') as string;
if (!title) {
throw new Error('Title is required');
}
await db.todo.create({ data: { title, completed: false } });
// Revalidate cache for the homepage!
revalidatePath('/');
}
Invoking from a Form (Progressive Enhancement):
// app/page.tsx - Server Component
import { createTodo } from '@/app/actions';
export default function TodoPage() {
return (
<main className="p-6">
<form action={createTodo} className="flex gap-2">
<input
type="text"
name="title"
placeholder="New Todo..."
className="border p-2 rounded"
required
/>
<button type="submit" className="bg-blue-600 text-white px-4 py-2 rounded">
Add Todo
</button>
</form>
</main>
);
}
Why Server Actions are Powerful
- Progressive Enhancement: Forms submitted using Server Actions work even before JavaScript finishes loading on the client!
- Zero API Boilerplate: Eliminates the need to construct manual
POSTendpoints inroute.ts. - Automatic Security: Next.js automatically secures Server Actions with POST-only requests, CORS headers, and encrypted action IDs.
Server Actions vs Traditional API Routes
| Feature | Traditional API Route (route.ts) | Server Action ('use server') |
|---|---|---|
| Primary Purpose | REST APIs for external consumers | React UI state mutations & form handling |
| Invoked Via | fetch('/api/todos', { method: 'POST' }) | Native <form action={myAction}> or JS invocation |
| Progressive Enhancement | No (Requires JS for fetch) | Yes (Works without JS enabled) |
| Cache Integration | Manual revalidation setup | Direct revalidatePath / revalidateTag calls |
TL;DR
- Server Actions are marked with the
'use server'directive. - Pass Server Actions to the
actionprop of standard HTML<form>elements. - Server Actions support Progressive Enhancement out of the box.
- Call
revalidatePath()inside Server Actions to refresh the user interface automatically.