Next.js Server Actions: Forms, Validation, and useActionState
Actions are POST endpoints the app can call. Schema validation on the server, serializable state for field errors, progressive enhancement, and why redirect() must not sit in a try block.

Quick Summary
A Server Action is an async function marked "use server" that the client can call as if it were local. The framework serializes the call, POSTs it to the server, runs the function there, and returns the result through the RSC stream. That means no API route, no fetch, no manual JSON handling — and no way to call it from anything other than your own app.
For forms, the action receives FormData and can be passed straight to <form action={...}>. With React 19's useActionState you get the previous return value, a wrapped action and a pending flag in one hook, which is the idiomatic way to render validation errors without a client store. useFormStatus reads the pending state from inside a child component of the form, and useOptimistic renders the expected result before the server confirms it.
Validation belongs on the server regardless of what the client did. Parse FormData with a schema, return a serializable state object for expected failures, and reserve throwing for genuinely unexpected errors — a thrown error reaches the nearest error.tsx and loses the field-level detail the user needs.
Basic Syntax & Core Signatures
// app/actions/contact.ts
"use server";
import { z } from "zod";
import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
const schema = z.object({
name: z.string().min(1, "Name is required").max(80),
email: z.string().email("Enter a valid email"),
message: z.string().min(10, "At least 10 characters"),
});
export type ContactState = {
ok: boolean;
errors?: Record<string, string[]>;
values?: Record<string, string>;
};
export async function submitContact(
_prev: ContactState,
formData: FormData
): Promise<ContactState> {
const parsed = schema.safeParse(Object.fromEntries(formData));
if (!parsed.success) {
return {
ok: false,
errors: parsed.error.flatten().fieldErrors,
values: { name: String(formData.get("name") ?? "") },
};
}
await db.message.create({ data: parsed.data });
revalidatePath("/admin/messages");
redirect("/thanks"); // throws; must be outside try/catch
}// app/contact/contact-form.tsx
"use client";
import { useActionState } from "react";
import { useFormStatus } from "react-dom";
import { submitContact, type ContactState } from "@/app/actions/contact";
const initial: ContactState = { ok: false };
export function ContactForm() {
const [state, formAction] = useActionState(submitContact, initial);
return (
<form action={formAction}>
<input name="name" defaultValue={state.values?.name} />
{state.errors?.name && <p role="alert">{state.errors.name[0]}</p>}
<input name="email" type="email" />
{state.errors?.email && <p role="alert">{state.errors.email[0]}</p>}
<textarea name="message" />
<SubmitButton />
</form>
);
}
function SubmitButton() {
const { pending } = useFormStatus(); // must be a child of the form
return <button disabled={pending}>{pending ? "Sending…" : "Send"}</button>;
}// Optimistic update without a client store
"use client";
const [optimistic, addOptimistic] = useOptimistic(items, (cur, next: Item) => [...cur, next]);Key Comparison Table
| Approach | Client code | Progressive enhancement | Revalidation |
|---|---|---|---|
Server Action on <form action> | None required | Works without JS | revalidatePath/revalidateTag |
Server Action from onClick | Yes | No | Same |
Route Handler + fetch | Yes | n/a | Manual |
useActionState | Yes | Form still submits | Same |
| Hook | Returns | Use for |
|---|---|---|
useActionState(action, initial) | [state, formAction, isPending] | Validation errors, result state |
useFormStatus() | { pending, data, method, action } | Submit button state |
useOptimistic(state, reducer) | [optimistic, update] | Instant UI before confirmation |
| Failure kind | Handling |
|---|---|
| Validation | Return state with errors |
| Auth expired | redirect("/login") |
| Not found | notFound() |
| Unexpected exception | Let it throw to error.tsx |
| Success with redirect | redirect() (throws by design) |
Practical Edge Cases & Deep Dives
1. redirect() throws — never wrap it in try
export async function save(formData: FormData) {
try {
await db.save(formData);
redirect("/done"); // throws NEXT_REDIRECT
} catch (e) {
return { ok: false, error: "Save failed" }; // swallows the redirect
}
}redirect() and notFound() signal by throwing a special error. A catch that swallows everything turns a successful redirect into an error message. The pattern is to keep the mutation in a try whose catch rethrows framework errors, or to return a result object and call redirect() after the try block.
2. Actions are POST endpoints with the app's origin check
A Server Action is a publicly reachable endpoint. Next.js compares the Origin header against the Host header and rejects cross-origin invocations, which stops the simplest CSRF, but the action itself must still authorize every call:
"use server";
export async function deletePost(id: string) {
const session = await auth();
if (!session?.user) throw new Error("unauthorized");
const post = await db.post.findUnique({ where: { id } });
if (post?.authorId !== session.user.id) throw new Error("forbidden");
await db.post.delete({ where: { id } });
revalidateTag("posts");
}Never trust a hidden field for identity — userId, tenantId, and prices all come from the client. Arguments are serialized and can be replayed by anyone who can reach the page, so authorization inside the action is the only authorization that counts.
3. useActionState and the shape of returned state
The action signature becomes (prevState, formData) when used with useActionState, and whatever it returns becomes the next prevState. That state must be serializable and should be minimal: field errors plus the submitted values the form needs to repopulate. A common mistake is returning FormData itself, which is not serializable, or returning the whole input including a password.
return { ok: false, errors: { password: ["Too short"] }, values: { email } };
// never echo secret fields backThe third tuple element, isPending, is available in React 19 and is the simplest spinner flag; useFormStatus remains necessary inside a shared submit button component because the hook only reads the nearest form's state.
4. Progressive enhancement: forms that work without JavaScript
Because <form action={serverAction}> compiles to a real form submission, it works before hydration. That is a real advantage for slow connections, and it breaks the moment the handler is on onClick instead. Keep the primary path as a form action, and treat client-side handlers as enhancements:
<form action={formAction}> {/* works without JS */}
<button type="button" onClick={() => ...}> {/* enhancement only */}Note that useActionState also works without JS: the browser submits, the server returns the new state, and React re-renders the page with it.
5. Long-running work and the request budget
An action runs inside the request that invoked it. There is no queue, no retry, and the platform's function timeout applies. Anything longer than a few seconds should be handed off — enqueue a job, return immediately, and let a worker update the database:
export async function importCsv(formData: FormData) {
const file = formData.get("file") as File;
const job = await queue.enqueue({ name: "import", payload: await file.text() });
revalidateTag("imports");
return { ok: true, jobId: job.id };
}The same reasoning applies to revalidateTag on a huge tag: invalidation is cheap, but the re-render it triggers on the next request is not.
Common Runtime & Configuration Mistakes
| Symptom | Cause | Fix |
|---|---|---|
Functions cannot be passed directly to Client Components | Passing an action from a client file without "use server" | Define it in a "use server" module or inline |
| Redirect silently ignored | redirect() inside try with a catch | Move it outside, or rethrow |
| Action returns stale state | Returning a non-serializable value | Return a plain object |
| Pending state never true | useFormStatus used outside the form | Move it into a child component |
useActionState action signature error | Used the single-argument form | (prevState, formData) |
| Validation passes on the client only | Trusting client checks | Re-validate with a schema on the server |
| Cross-origin action rejected | Missing/mismatched Origin | Use a same-origin form or a route handler |
| Secrets in the bundle | Action imported into a client module that is not "use server" | Move it to its own file |
| Timeout on a big import | Work done inside the request | Enqueue and poll |
| Page not updating after save | No revalidation call | revalidatePath/revalidateTag |
A Server Action is a function call over HTTP with the roughness removed: it needs the same authorization, validation, and idempotency thought as an endpoint, and it returns the state that lets the form explain what went wrong.
Try matching browser tools
All toolsSmall utilities that fit Next.js work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Next.js guides
All Next.js guidesNext.js Static Export, Standalone Output, and Docker Deployment
Export has no server, standalone has a pruned one, and the default expects a full install. The three COPY lines that decide whether a container renders CSS.
Next.js Parallel Routes and Intercepting Routes: Slot Layouts and Modals
Named slots render several pages in one layout, and (.) interception makes a click open over the page while a direct link renders the full route. Why every slot needs default.tsx.
Next.js ISR: Route Revalidate, revalidateTag, and On-Demand Invalidation
Two clocks and one trigger: route revalidate seconds, fetch-level tags, and a webhook that calls revalidateTag. A timer is a ceiling on freshness, never a guarantee.
Next.js Environment Variables: NEXT_PUBLIC_, Build-Time Inlining, and Runtime Config
The prefix decides whether a value is compiled into the browser bundle or stays on the server. One image, two environments, and the choice that follows from it.
More in Next.js
All Next.js guidesThe guides filed next to this one in Next.js, in library order.