Next.jsMedium

How do you handle form submissions with Server Actions?

Pass a Server Function to <form action={fn}>. The function receives FormData; validate it, perform the mutation, revalidate cached data, and either redirect() or return a state object. Wrap it with useActionState in a Client Component to show errors and pending state.

Step by step

  1. Define an action in a "use server" file. With useActionState, its signature is (prevState, formData) => newState.
  2. Authenticate and authorize.
  3. Parse with Zod (Object.fromEntries(formData) or formData.get(...)); return field errors as data.
  4. Mutate the database.
  5. updateTag(...) (or revalidatePath) so lists show the change.
  6. redirect("/somewhere") or return { ok: true }.

Client UX

  • useActionState(action, initialState) returns [state, formAction, isPending].
  • useFormStatus() inside a child component gives pending for the submit button.
  • useOptimistic shows the expected result immediately.
  • Use defaultValue from returned state to keep user input after a validation error.
  • Forms reset after a successful action in React 19; return the values if you need to keep them.

Progressive enhancement

Because action is a real form submission, it works before hydration. With useActionState, pass a permalink (third argument) for full progressive enhancement across pages.

Extra arguments

Bind values with action.bind(null, id), or use hidden inputs. Bound arguments are visible to the client, so still authorize on the server.

next/form

For search forms that navigate with GET, use <Form action="/search"> from next/form; it prefetches and navigates client-side.

Code example

tsx
1// app/signup/actions.ts
2"use server";
3
4import { z } from "zod";
5import { redirect } from "next/navigation";
6import { db } from "@/lib/db";
7
8const Schema = z.object({ email: z.string().email(), name: z.string().min(2) });
9export type State = { errors?: Record<string, string[]>; values?: Record<string, string> };
10
11export async function signup(_prev: State, formData: FormData): Promise<State> {
12 const values = Object.fromEntries(formData) as Record<string, string>;
13 const parsed = Schema.safeParse(values);
14 if (!parsed.success) return { errors: parsed.error.flatten().fieldErrors, values };
15
16 if (await db.user.findUnique({ where: { email: parsed.data.email } })) {
17 return { errors: { email: ["Email already registered"] }, values };
18 }
19 await db.user.create({ data: parsed.data });
20 redirect("/welcome");
21}
22
23// app/signup/form.tsx
24// "use client";
25// import { useActionState } from "react";
26// export function SignupForm() {
27// const [state, action, pending] = useActionState(signup, {});
28// return (
29// <form action={action}>
30// <input name="email" defaultValue={state.values?.email} /> {state.errors?.email?.[0]}
31// <input name="name" defaultValue={state.values?.name} /> {state.errors?.name?.[0]}
32// <button disabled={pending}>{pending ? "Creating…" : "Sign up"}</button>
33// </form>
34// );
35// }

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