Next.js Validate with Zod
Zod checks the form data on the server before anything is saved. One schema holds the rules.
One schema for the form
The schema names the two fields and their rules. Each rule carries its own error words.
import { z } from "zod";
export const bookFormSchema = z.object({
title: z.string().trim().min(1, "Title is required"),
author: z.string().trim().min(1, "Author is required"),
});A missing author fails the check
The check runs on a title with no author. The author error names the missing value.
node -e 'const { z } = require("zod"); const bookFormSchema = z.object({ title: z.string().trim().min(1, "Title is required"), author: z.string().trim().min(1, "Author is required") }); const parsed = bookFormSchema.safeParse({ title: "Some Book" }); console.log("Valid:", parsed.success); if (!parsed.success) console.log(JSON.stringify(z.flattenError(parsed.error).fieldErrors));'Example
node -e 'const { z } = require("zod"); const bookFormSchema = z.object({ title: z.string().trim().min(1, "Title is required"), author: z.string().trim().min(1, "Author is required") }); const parsed = bookFormSchema.safeParse({ title: "", author: "X" }); console.log("Valid:", parsed.success); if (!parsed.success) console.log(JSON.stringify(z.flattenError(parsed.error).fieldErrors));'Key points
- Zod: a tool that checks data against a schema and reports what is wrong
- Schema: one object that states the rules for the form fields
- The title rule is a string, trimmed, of at least one character.
- The author rule is the same: a string, trimmed, of at least one character.
- safeParse runs the check without throwing. It answers ok or not ok.
- A failed check returns the field errors. Nothing is saved.
In this example, the script checks an empty title against the schema. The check answers Valid: false, and the field errors name the title: Title is required. The same schema runs in the action and in the API route, and both refuse the book. The form shows that error beside the title field, and the book is never saved.
Note
The check runs on the server, so a reader cannot skip it from the browser.
Try it Yourself
Edit the code, then press Run.
Running is simulated · TypeScript Playground
Exercise
What does the schema say about an empty title?