Next.jsMedium
What are Server Actions in Next.js?
Server Actions are async functions marked with "use server" that run on the server but can be called from the client, typically from a <form action> or an event handler. React docs now call them Server Functions; "Server Action" refers to one used for a mutation via forms or transitions.
How they work
- Next.js gives each action an encrypted ID and creates a hidden POST endpoint on the page that uses it.
- Calling the action from the client sends a POST with serialized arguments; the result returns in the same response as updated UI (the RSC payload), so one round-trip gives both data and fresh UI.
- Unused actions are removed from the client bundle and get no endpoint.
Features
- Progressive enhancement: a
<form action={serverAction}>works before JavaScript loads. - Integrated caching: call
updateTag,revalidateTag,revalidatePathorrefresh()inside the action and the client cache updates in the same response. redirect()after the mutation.- React hooks:
useActionStatefor results and errors,useFormStatusfor pending state,useOptimisticfor instant UI.
Security essentials
- Every action is a public HTTP endpoint. Authenticate and authorize inside each one; hiding the button is not protection.
- Validate inputs (Zod) and return only what the UI needs.
- Built-in CSRF protection compares
OriginwithHost. ConfigureserverActions.allowedOriginsbehind proxies. - Default body limit is 1MB (
serverActions.bodySizeLimit). - Self-hosted multi-instance apps should set
NEXT_SERVER_ACTIONS_ENCRYPTION_KEY.
Limits
Actions run one at a time per client (queued), so they are a poor fit for parallel data reads. Use Server Components or Route Handlers to read data.
Code example
tsx
1// app/todos/actions.ts2"use server";34import { z } from "zod";5import { updateTag } from "next/cache";6import { verifySession } from "@/lib/auth";7import { db } from "@/lib/db";89const Todo = z.object({ title: z.string().min(1).max(200) });1011export async function addTodo(_prev: { error?: string }, formData: FormData) {12 const user = await verifySession(); // authorize every call13 const parsed = Todo.safeParse({ title: formData.get("title") });14 if (!parsed.success) return { error: "Title is required" };1516 await db.todo.create({ data: { title: parsed.data.title, userId: user.id } });17 updateTag(`todos:${user.id}`); // user sees the new todo immediately18 return {};19}2021// app/todos/form.tsx22// "use client";23// import { useActionState } from "react";24// const [state, action, pending] = useActionState(addTodo, {});25// <form action={action}><input name="title" /><button disabled={pending}>Add</button>{state.error}</form>
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the Next.js set.