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
- Define an action in a
"use server"file. WithuseActionState, its signature is(prevState, formData) => newState. - Authenticate and authorize.
- Parse with Zod (
Object.fromEntries(formData)orformData.get(...)); return field errors as data. - Mutate the database.
updateTag(...)(orrevalidatePath) so lists show the change.redirect("/somewhere")or return{ ok: true }.
Client UX
useActionState(action, initialState)returns[state, formAction, isPending].useFormStatus()inside a child component givespendingfor the submit button.useOptimisticshows the expected result immediately.- Use
defaultValuefrom 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
1// app/signup/actions.ts2"use server";34import { z } from "zod";5import { redirect } from "next/navigation";6import { db } from "@/lib/db";78const Schema = z.object({ email: z.string().email(), name: z.string().min(2) });9export type State = { errors?: Record<string, string[]>; values?: Record<string, string> };1011export 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 };1516 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}2223// app/signup/form.tsx24// "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.