Lesson 13 of 27Full-stack
Server Actions and Forms
Mutate data with Server Actions, validate forms with Zod, show pending and error states, and secure every action.
Reading data is half an app. The other half is changing it: sign-ups, comments, settings, checkouts. Server Actions let a form call a function on your server directly, with no hand-written API route and no fetch boilerplate. They also create a public endpoint for every function you write, which is exactly why interviewers ask how you secure them.
A function the browser can call
A Server Function is an async function marked with the "use server" directive. Next.js gives it a hidden ID and an HTTP endpoint, so client code can call it over the network as if it were a local function. When you use one for a form submission or a mutation, it is called a Server Action.
Put "use server" at the top of a file to turn every export into a Server Function:
"use server";
import { updateTag } from "next/cache";
import { redirect } from "next/navigation";
import { db } from "@/db";
import { posts } from "@/db/schema";
import { verifySession } from "@/lib/dal";
export async function createPost(formData: FormData) {
const session = await verifySession(); // who is calling? (always check)
const title = String(formData.get("title") ?? "");
const body = String(formData.get("body") ?? "");
const [post] = await db.insert(posts).values({ title, body, authorId: session.userId }).returning();
updateTag("posts"); // lists of posts show the new one
redirect(`/posts/${post.id}`); // throws: keep it last
}Then pass it to a form. The function receives the form's fields as a standard FormData object:
import { createPost } from "../actions";
export default function NewPostPage() {
return (
<form action={createPost}>
<input name="title" required />
<textarea name="body" required />
<button type="submit">Publish</button>
</form>
);
}That page is a Server Component with no client JavaScript of its own, and the form still works. If JavaScript has not loaded (or is disabled), the browser submits it as a normal HTML form post. This is progressive enhancement: the baseline works everywhere, and JavaScript makes it smoother when available.
You can also define an action inline inside a Server Component by putting "use server" as the first line of an async function body. Client Components cannot define actions, but they can import them from a "use server" file or receive them as props.
What happens on submit
Actions always use POST to the current route.
Put the work inside a typical Server Action in order.
- Tap the steps below in the right order.
Pending and error states with useActionState
Real forms need feedback: a disabled button while saving, field errors when input is bad. React 19's useActionState hook, covered in depth in the React lesson Actions and Optimistic UI, wraps an action and gives you three things: the latest state the action returned, a formAction to pass to the form, and a pending flag.
The action's signature changes to (previousState, formData), and it returns the next state instead of throwing for expected problems like a bad email. Try it. This version runs entirely in the browser, with an async function standing in for the server:
In a Next.js app the Client Component looks the same, except saveName is imported from a "use server" file. One more hook, useFormStatus from react-dom, reads the pending state of the parent form, which is handy for a reusable submit button:
"use client";
import { useFormStatus } from "react-dom";
export function SubmitButton({ children }: { children: React.ReactNode }) {
const { pending } = useFormStatus(); // must be rendered inside a <form>
return <button disabled={pending}>{pending ? "Working..." : children}</button>;
}Match each tool to its job.
Calling actions outside forms
Not every mutation is a form. A like button, a drag-and-drop reorder, an autosave on blur: these call the action from an event handler. An action imported into a Client Component is just an async function, so you can call it directly. Wrap the call in startTransition so React tracks it as an Action: you get a pending flag, and the UI update that arrives with the response is applied as one transition instead of a flash of half-new state.
"use client";
import { useTransition } from "react";
import { likePost } from "../actions";
export function LikeButton({ postId, likes }: { postId: string; likes: number }) {
const [isPending, startTransition] = useTransition();
return (
<button
disabled={isPending}
onClick={() => startTransition(async () => { await likePost(postId); })}
>
{likes} likes
</button>
);
}Two other shapes come up often, and both keep progressive enhancement because they are still forms:
import { archivePost, deletePost } from "../actions";
// Inside the page component:
const archive = archivePost.bind(null, post.id); // pre-fill the first argument
<form action={archive}>
<button>Archive</button>
{/* A second button in the same form can call a different action */}
<button formAction={deletePost}>Delete</button>
</form>.bind(null, post.id) gives you an action whose first argument is fixed, so the signature becomes archivePost(postId, formData). That reads nicely, but remember what it is: the bound value travels to the browser and comes back as an ordinary argument. Unlike variables an inline action captures in its closure, bound arguments are not encrypted, and a caller can replace them. Treat postId exactly like a form field: check that this user may archive this post.
A few rules that save debugging time:
- Arguments and return values must be serializable by React: strings, numbers, plain objects, arrays,
Date,FormData,Map,Set, Promises. Class instances and functions are not. - Actions run one at a time per client. The Next.js router queues them and sends the next only after the previous finishes. Ten rapid clicks become ten sequential round trips, so debounce chatty calls like autosave.
- Do not fetch data with actions. They are POST requests, they are not cached, and they queue behind each other. Read data in Server Components or a Route Handler.
<form action={archivePost.bind(null, post.id)}> renders on a page only the post's author can see. Inside archivePost(postId, formData), what must you still do?Optimistic updates with server data
The React lesson Actions and Optimistic UI covered how useOptimistic works: an optimistic layer over real state that disappears when the Action ends. In Next.js there is one useful twist. The real state usually is not useState at all. It is a prop that came from a Server Component, and the action's response re-renders that Server Component with fresh data.
import { getTodos } from "@/lib/todos";
import { TodoList } from "./TodoList";
export default async function TodosPage() {
const todos = await getTodos(); // cached and tagged "todos"
return <TodoList todos={todos} />;
}"use server";
import * as z from "zod";
import { updateTag } from "next/cache";
import { verifySession } from "@/lib/dal";
import { insertTodo } from "@/lib/todos";
const Title = z.string().trim().min(1).max(200);
export async function addTodo(title: string) {
const session = await verifySession();
const parsed = Title.safeParse(title);
if (!parsed.success) return { error: "Give the todo a title." };
await insertTodo(session.userId, parsed.data);
updateTag("todos"); // the response carries a re-rendered page with the new list
return { ok: true };
}"use client";
import { useOptimistic, useState } from "react";
import { addTodo } from "./actions";
import type { Todo } from "@/lib/todos";
type Row = Todo & { pending?: boolean };
export function TodoList({ todos }: { todos: Todo[] }) {
const [error, setError] = useState("");
const [rows, addRow] = useOptimistic<Row[], Row>(todos, (current, row) => [...current, row]);
async function submit(formData: FormData) {
const title = String(formData.get("title") ?? "").trim();
if (!title) return;
setError("");
addRow({ id: crypto.randomUUID(), title, pending: true }); // id made here, not in the reducer
const result = await addTodo(title);
if (result.error) setError(result.error); // the optimistic row vanishes by itself
}
return (
<>
<ul>
{rows.map((t) => (
<li key={t.id} style={{ opacity: t.pending ? 0.5 : 1 }}>{t.title}</li>
))}
</ul>
<form action={submit}>
<input name="title" aria-label="New todo" />
<button>Add</button>
</form>
{error && <p role="alert">{error}</p>}
</>
);
}Follow one submit. addRow shows the greyed row at once. addTodo runs on the server, writes, and calls updateTag("todos"). Because the action invalidated data the page uses, Next.js re-renders the page in the same response, so the browser receives a new todos prop with the real row in it. When the transition ends, React drops the optimistic layer and shows the real list. There is no setTodos anywhere: the server is the source of truth, and the optimistic row only covers the round trip.
Three details matter here. Generate the temporary id in the handler, because the update function can run more than once and must be pure. Give the real and temporary rows different ids, or React will reuse the wrong list item. And if the action throws instead of returning an error, the optimistic row still rolls back, but the error goes to the nearest error boundary; the lesson Error Handling in Next.js covers when to return and when to throw.
Validating with Zod
Form data is untrusted. Even with required on the input, anyone can POST anything. Validate on the server with a schema library such as Zod: you describe the shape once, and safeParse returns either typed data or structured errors.
"use server";
import * as z from "zod";
const SignupSchema = z.object({
name: z.string().trim().min(2, { error: "Name must be at least 2 characters." }),
email: z.email({ error: "Enter a valid email." }),
password: z.string().min(8, { error: "Use at least 8 characters." }),
});
export type SignupState = { errors?: Record<string, string[]>; message?: string };
export async function signup(prev: SignupState, formData: FormData): Promise<SignupState> {
const parsed = SignupSchema.safeParse(Object.fromEntries(formData));
if (!parsed.success) {
return { errors: z.flattenError(parsed.error).fieldErrors };
}
// parsed.data is fully typed: { name: string; email: string; password: string }
// ...create the user, start a session, redirect...
return { message: "Account created" };
}fieldErrors is an object like { email: ["Enter a valid email."] }, ready to render next to each input. The same idea without a library:
Press Run (⌘ Enter) to see what happens.What does this print?
const fields: Record<string, string> = { name: "Sam", email: "sam@x" };
const errors: string[] = [];
if (fields.name.trim().length < 2) errors.push("name");
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(fields.email)) errors.push("email");
console.log(errors.join(",") || "ok");Field errors: flattenError or treeifyError
Zod 4 gives you two ways to turn a failed parse into something a form can render. Both are top-level functions on z.
z.flattenError(error) returns { formErrors, fieldErrors }. fieldErrors is keyed by top-level field name, which is exactly what a flat form needs. formErrors holds errors that belong to the whole object, such as a .refine() check that "passwords must match" with no path.
z.treeifyError(error) keeps the full shape: { errors, properties: { name: { errors }, tags: { errors, items: [...] } } }. Use it when the form has nested objects or repeating rows (line items on an invoice, a list of addresses), because flattening collapses items.2.price into a single items key and you can no longer say which row is wrong.
For a schema with a tags array where the second tag is empty, the two shapes differ like this:
z.flattenError(err).fieldErrors;
// { name: ["short"], email: ["bad email"], tags: ["Too small: expected string to have >=1 characters"] }
z.treeifyError(err).properties?.tags;
// { errors: [], items: [ <empty>, { errors: ["Too small: expected string to have >=1 characters"] } ] }The older error.flatten() and error.format() methods are deprecated in Zod 4. You will still see them in tutorials, so recognise them, but write the top-level functions.
One React 19 behaviour catches every team once. After a form action finishes, React resets uncontrolled fields, even when your action returned errors. The user submits, sees "Enter a valid email", and finds every input empty. The fix is to return the submitted values in the state and feed them back as defaultValue:
export type SignupState = {
errors?: Record<string, string[]>;
values?: { name?: string; email?: string }; // never echo the password
};
// in signup(): on failure
return {
errors: z.flattenError(parsed.error).fieldErrors,
values: { name: String(formData.get("name") ?? ""), email: String(formData.get("email") ?? "") },
};<input name="email" defaultValue={state.values?.email} aria-invalid={!!state.errors?.email} aria-describedby="email-error" />
{state.errors?.email && <p id="email-error">{state.errors.email[0]}</p>}The aria-invalid and aria-describedby pair makes screen readers announce the error with the field, which is the accessible version of "red text under the input".
Invalidating after a mutation
A write is only half done until the user sees it. After the database changes, the action has to tell Next.js which cached data is now wrong. There are four tools, and picking the wrong one is a common source of "I saved it but the page still shows the old value" bugs.
| Call | Where it works | What it does |
|---|---|---|
updateTag("posts") | Server Actions only | Expires the tag now. The action's own response waits for fresh data, so the user reads their own write. |
revalidateTag("posts", "max") | Actions and Route Handlers | Marks the tag stale. The next request gets the old value while a fresh one is fetched in the background. |
revalidatePath("/posts") | Actions and Route Handlers | Invalidates everything cached for one route. Coarse but simple. |
refresh() | Server Actions only | Touches no cache. It tells the client router to re-fetch the current page's uncached, dynamic parts. |
All four import from next/cache. The rule of thumb: inside an action that a user is waiting on, reach for updateTag. It gives read-your-own-writes, and calling it from anywhere else throws. In a webhook from your CMS or payment provider, which is a Route Handler, use revalidateTag with a profile; the one-argument form is deprecated and logs a warning. Use revalidatePath when the data is not tagged, and pass the real path (/blog/hello), because a pattern like /blog/[slug] does nothing unless you also pass "page" or "layout".
refresh() is the odd one out. Suppose a header shows an unread-notifications count that is read per request from the database, with no use cache and no tag. An action marks a notification as read. Nothing cached changed, so updateTag has nothing to expire, yet the browser still shows the old count from its client-side router cache. refresh() tells the client to fetch the current route's dynamic data again in the action's response. If the action already called updateTag or revalidatePath, the page is re-rendered anyway and you do not need it.
How tags, cacheLife profiles and the client cache fit together is the subject of Cache Components in Depth; here you only need to pick the right call after a write.
Match each situation to the call that fits it best.
Securing actions
The common mistakes:
- Trusting IDs from the form. A hidden
<input name="userId">can be edited. Get the user from the session on the server, and check that they own the record they are changing. - Skipping authorization. "Logged in" is not "allowed". Check that this user may delete this post.
- Returning too much. Whatever an action returns is sent to the browser. Return only what the UI needs.
Next.js adds some protection for you: action IDs are unguessable and unused actions are removed from the build, the variables an inline action captures (its closure) are encrypted before being sent to the client, and actions only accept POST requests from your own origin by default. These reduce risk; they do not replace your checks.
"use server";
import { updateTag } from "next/cache";
import { verifySession } from "@/lib/dal";
import { getPost, removePost } from "@/lib/posts";
export async function deletePost(postId: string) {
const session = await verifySession(); // 1. authenticated?
const post = await getPost(postId);
if (!post || post.authorId !== session.userId) { // 2. authorized for THIS post?
return { error: "Not allowed" };
}
await removePost(postId);
updateTag("posts");
return { ok: true };
}try { await save(); redirect("/done"); } catch (e) { return { error: "Failed" }; }. Saving succeeds. What does the user see?Rate limiting and idempotency
Authentication stops strangers. It does not stop a logged-in user, or a script holding a stolen session, from calling sendInvite ten thousand times. And it does not stop the most common duplicate of all: a user on a slow train who taps "Pay" twice. These are two different problems with two different fixes.
Rate limiting caps how often one caller may run an action. Pick a key (the user ID when there is a session, the client IP when there is not), count calls in a time window, and refuse once the count passes the limit. Put the check at the top of the action, before any expensive work:
"use server";
import { headers } from "next/headers";
import { verifySession } from "@/lib/dal";
import { rateLimit } from "@/lib/rate-limit"; // backed by Redis or similar
export async function sendInvite(prev: InviteState, formData: FormData): Promise<InviteState> {
const session = await verifySession();
const { ok } = await rateLimit(`invite:${session.userId}`, { limit: 20, windowSeconds: 3600 });
if (!ok) return { message: "Too many invites. Try again in an hour." };
// ...validate, authorize, send...
return { message: "Invite sent" };
}
// For anonymous actions such as sign-up, key on the client IP instead:
async function clientIp() {
const h = await headers(); // async since Next.js 15
return h.get("x-forwarded-for")?.split(",")[0]?.trim() ?? "unknown";
}The counter must live in a shared store. On serverless platforms and in any multi-instance deployment, each instance has its own memory, so an in-process Map gives every instance its own allowance and the limit means nothing. Redis (or a hosted Redis-compatible service) with an atomic increment is the usual choice; some platforms also offer rate limiting at the firewall. And only trust x-forwarded-for when you know your host or proxy sets it, because a client can send that header itself.
Idempotency means running the same request twice has the same effect as running it once. Disabling the button while pending stops most double clicks, but not a network retry, a second tab, or a user who presses back and submits again. The reliable fix is an idempotency key: a unique value created when the form renders and sent with the submission. The action records the key with the result, and a second request with the same key returns the stored result instead of acting again.
The key was rendered into a hidden input when the checkout page loaded.
Two details decide whether this works in production. First, enforce the key with a unique constraint in the database (INSERT ... ON CONFLICT DO NOTHING, then read the existing row), not with a "check, then insert" in code, because two requests can both pass the check before either inserts. Second, create the key in a dynamic render. If the checkout page is prerendered or inside use cache, every visitor receives the same key and the second customer's order is treated as a duplicate of the first. Treat the key like any form field: scope it to the user so one user cannot replay another's key. Transactions and constraints in detail belong to Databases and the Data Access Layer.
Here is the logic of both, with an in-memory Map standing in for Redis and the database. Change the limit or the timestamps and run it again.
Press Run (⌘ Enter) to see what happens.What does this print?
const seen = new Map<string, number>();
let charges = 0;
function pay(key: string): number {
const earlier = seen.get(key);
if (earlier !== undefined) return earlier;
charges += 1;
seen.set(key, charges);
return charges;
}
pay("a");
pay("a");
pay("b");
pay("a");
console.log(charges, pay("b"));Rate limits and idempotency are part of a wider checklist for actions and route handlers, alongside origin checks and security headers, covered in Securing a Next.js App.
Validate a form in a Server Action
A Server Action receives untrusted form input. Write validateRsvp(fields) that returns field errors the form can display, the same shape Zod's flattenError(...).fieldErrors gives you.
fields is a plain object of strings (a missing field counts as ""). Rules:
name: trimmed, at least 2 characters, else"Name must be at least 2 characters."email: trimmed, must match/^[^\s@]+@[^\s@]+\.[^\s@]+$/, else"Enter a valid email."guests: a whole number from 0 to 4 written with digits only, else"Guests must be a whole number from 0 to 4."
On success return { ok: true, data: { name, email, guests } } with name trimmed, email trimmed and lowercased, and guests as a number. On failure return { ok: false, errors } where errors only has keys for fields that failed, each an array with one message.
{ name: " Ada ", email: "ADA@x.io", guests: "2" }
→ { ok: true, data: { name: "Ada", email: "ada@x.io", guests: 2 } }A form with useActionState
Build the client half of a Server Action form. In a real app subscribe would live in app/actions.ts with "use server"; here it is a local async function so it runs in the browser.
Use useActionState(subscribe, initialState) so that:
- the form has a text input named
emailand a submit button labelled Join - while the action runs, the button shows Joining... and is disabled
- if the email has no
@, show the error Enter a valid email. - on success, replace the form with Subscribed: followed by the email, for example
Subscribed: ada@example.com
subscribe(prevState, formData) must return the next state; do not throw for a bad email.
- Server Function
- An async function marked
"use server"that client code can call over the network via a POST request. - Server Action
- A Server Function used for a mutation, typically passed to
<form action>orformAction. - useActionState
- React hook that wraps an action as
(prevState, formData)and returns[state, formAction, pending]. - progressive enhancement
- Building the feature to work with plain HTML first (a form post), then improving it when JavaScript loads.
- safeParse
- Zod method that validates input and returns
{ success, data }or{ success: false, error }instead of throwing. - authorization
- Checking that a known user is allowed to perform this specific operation on this specific record.
- updateTag
- A
next/cachecall, Server Actions only, that expires a cache tag at once so the user reads their own write. - refresh()
- A
next/cachecall, Server Actions only, that re-fetches the current page's uncached dynamic data without touching any cache. - idempotency key
- A unique value sent with a request so the server can recognise a repeat and return the first result instead of acting twice.
- rate limit
- A cap on how many times one caller (user ID or IP) may run an operation in a time window, counted in a shared store.