advanced
Server Actions
Mutate data from forms or client events through server functions with validation, auth, and revalidation.
Server Actions are async server functions invoked from forms or client events. They run on the server with access to secrets and databases, then can revalidate caches or redirect.
'use server';
export async function createPost(formData: FormData) {
const title = String(formData.get('title'));
await db.post.create({ data: { title } });
revalidatePath('/posts');
}
Validate input, enforce auth, and treat actions like HTTP mutations — idempotency and error shapes matter.
On interviews: contrast actions with route handlers and explain revalidation after writes.
Common pitfalls: skipping auth in actions, trusting client-hidden fields, and missing error feedback to the UI.
The trade-off is ergonomic mutations versus needing clear security and cache invalidation discipline.
Checklist:
- Validate and authorize every action.
- Revalidate tags or paths after mutations.
- Return structured errors for forms.
- Do not expose internal errors to clients.