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, revalidatePath or refresh() inside the action and the client cache updates in the same response.
  • redirect() after the mutation.
  • React hooks: useActionState for results and errors, useFormStatus for pending state, useOptimistic for 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 Origin with Host. Configure serverActions.allowedOrigins behind 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.ts
2"use server";
3
4import { z } from "zod";
5import { updateTag } from "next/cache";
6import { verifySession } from "@/lib/auth";
7import { db } from "@/lib/db";
8
9const Todo = z.object({ title: z.string().min(1).max(200) });
10
11export async function addTodo(_prev: { error?: string }, formData: FormData) {
12 const user = await verifySession(); // authorize every call
13 const parsed = Todo.safeParse({ title: formData.get("title") });
14 if (!parsed.success) return { error: "Title is required" };
15
16 await db.todo.create({ data: { title: parsed.data.title, userId: user.id } });
17 updateTag(`todos:${user.id}`); // user sees the new todo immediately
18 return {};
19}
20
21// app/todos/form.tsx
22// "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.

Open in study app