Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

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.

~4 min readNext.js
#Next.js#Server Actions#Forms#React 19
3D illustration of a form panel sending data through a function pipe into a server cube with validation checkmarks

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

ts
// 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 }
tsx
// 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>; }
tsx
// Optimistic update without a client store "use client"; const [optimistic, addOptimistic] = useOptimistic(items, (cur, next: Item) => [...cur, next]);

Key Comparison Table

ApproachClient codeProgressive enhancementRevalidation
Server Action on <form action>None requiredWorks without JSrevalidatePath/revalidateTag
Server Action from onClickYesNoSame
Route Handler + fetchYesn/aManual
useActionStateYesForm still submitsSame
HookReturnsUse 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 kindHandling
ValidationReturn state with errors
Auth expiredredirect("/login")
Not foundnotFound()
Unexpected exceptionLet it throw to error.tsx
Success with redirectredirect() (throws by design)

Practical Edge Cases & Deep Dives

1. redirect() throws — never wrap it in try

ts
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:

ts
"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.

ts
return { ok: false, errors: { password: ["Too short"] }, values: { email } }; // never echo secret fields back

The 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:

tsx
<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:

ts
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

SymptomCauseFix
Functions cannot be passed directly to Client ComponentsPassing an action from a client file without "use server"Define it in a "use server" module or inline
Redirect silently ignoredredirect() inside try with a catchMove it outside, or rethrow
Action returns stale stateReturning a non-serializable valueReturn a plain object
Pending state never trueuseFormStatus used outside the formMove it into a child component
useActionState action signature errorUsed the single-argument form(prevState, formData)
Validation passes on the client onlyTrusting client checksRe-validate with a schema on the server
Cross-origin action rejectedMissing/mismatched OriginUse a same-origin form or a route handler
Secrets in the bundleAction imported into a client module that is not "use server"Move it to its own file
Timeout on a big importWork done inside the requestEnqueue and poll
Page not updating after saveNo revalidation callrevalidatePath/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 tools

Small utilities that fit Next.js work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Next.js guides

More in Next.js

All Next.js guides

The guides filed next to this one in Next.js, in library order.