Next.js Server-Side Form Validation
Validate forms in Next.js App Router using server actions with Zod schema validation. Returns typed error objects to the client component and prevents.
Code
import { z } from 'zod';
const schema = z.object({
email: z.string().email('Invalid email'),
password: z.string().min(8, 'Min 8 characters'),
});
export async function loginAction(formData: FormData) {
const parsed = schema.safeParse({
email: formData.get('email'),
password: formData.get('password'),
});
if (!parsed.success) {
return { errors: parsed.error.flatten().fieldErrors };
}
const user = await authenticate(parsed.data);
return { user };
}How the snippet works
Count the function loginAction as the entire surface area of Next.js Server-Side Form Validation.
The asynchronous flow is linearized with await, keeping failure handling local. z are the only symbols borrowed from zod — the coupling is explicit and narrow.
Returns a newly built value, leaving the inputs as they were.
What to watch for
- Plan for an install step:
zodis a real dependency, resolved by the package manager. - The guard
!parsed.successshort-circuits the flow with an earlyreturnwhen its condition holds.
Applying it
The main signature reads export async function loginAction(formData: FormData)
loginAction is what another module would consume; nothing else here is load-bearing for callers.
Statements that matter
return { errors: parsed.error.flatten().fieldErrors };
const user = await authenticate(parsed.data);
return { user };
Interactive Tools for This Topic
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.Credit Card Brand DetectorIdentify the card network from a number's prefix and length, validate the Luhn checksum, and show a masked form and the issuer identification number.
FAQ
- Does `loginAction` modify its input?
- No. Nothing passed in is written to, which makes the call safe on shared data.
- Which packages must be installed first?
- Yes. The imports resolve to `zod`, which the package manager must provide.
Report a problem with this exampleOpens a pre-filled issue on GitHub.