Zod validation in TypeScript: check data once, at the door
From the work/ 12 min read
One zod schema for the form, the API route and the type: safeParse, a 400 with field errors, z.infer and messages people can act on. Tested with zod 4.6.7.
- JavaScript
- Next.js
- Security
In this article (9)
Zod validation belongs in one place: where data enters your code. Check the form before it is sent and the API route before anything is saved. Define a schema with z.object, check input with safeParse, answer 400 when it fails, and get the TypeScript type from z.infer instead of writing it twice.
Below is the full example with zod 4.6.7, the latest version on npm as of November 19, 2026: an order schema, the function that checks the form, the component, and a Next.js API route that rejects bad input with a 400. We ran it on Node 22 and type-checked it with tsc --strict.
Zod validation: check once, at the door
Data from outside your code is not the type your code says it is. A form sends strings. A fetch call sends whatever its author wrote. A response from another API or from an AI model can change shape without warning. TypeScript checks your code at compile time; at runtime it sees nothing. Trust the type and the bug shows up three functions later, as a NaN in a total or an undefined in the database.
The rule is to check at the boundary: at the exact point where data comes in, once. Past that point, the rest of the code works with an object that already matches the schema and never asks again whether quantity is a number. Validating in the middle of the code means scattering loose if checks across functions, and they drift apart the moment someone adds a field.
A store has three usual entry points: the form (the browser), the API route (the server) and responses from outside services. The server one is mandatory. Browser checks help the person filling in the form, but anyone can call your API without it. It is the same reason CORS does not protect your API: what protects it is checking every request on the server.
Scroll the figure sideways to see all of it
Define the schema
A zod schema describes the shape of the data and its rules. Install it with npm install zod. Per the zod docs, it is tested against TypeScript 5.5 and later and requires strict in tsconfig.json. Zod 4 has been stable since 4.0.0, published on July 9, 2025, and 4.6.7 shipped on npm on October 12, 2026. Here is an order schema:
// lib/order-schema.ts
import * as z from "zod";
export const OrderInput = z.object({
name: z.string().trim().min(2, "Write your full name"),
email: z.string().trim().pipe(z.email("Check your email address")),
postalCode: z.string().trim().regex(/^\d{5}$/, "A postal code has 5 digits"),
quantity: z.coerce.number("Enter a number").int("Whole units only").min(1, "Order at least 1").max(10, "Up to 10 per order"),
notes: z.string().trim().max(500, "Notes: 500 characters max").optional(),
});
export type OrderInput = z.infer<typeof OrderInput>;
import * as z from "zod"is the import the zod 4 docs use.z.objectdefines the object. By default, keys that are not in the schema are stripped from the result without an error, per the API reference.name:.trim()removes whitespace before the length check, and.min(2, "...")requires two characters with a custom message.email: trims first, then.pipe()hands the clean string toz.email(). Order matters: we triedz.email().trim()and it rejects" ana@example.com ", because the format check runs before the trim. That trailing space is what a phone keyboard leaves after autofill, as covered in mobile checkout autocomplete.postalCode: five digits with.regex(). It stays a string so the leading zero in06700survives.quantity:z.coerce.number()converts the form's string withNumber(input). Its message is used when the result is not a number. Then.int(),.min(1)and.max(10), each with its own message.notes: optional, 500 characters at most.z.inferderives the type from the schema. Type and schema share the nameOrderInput: TypeScript allows a value and a type with the same name, so one import brings both.
These are the checks that come up most in a store form, and what each one catches. We ran all of them on zod 4.6.7:
| Field | Schema | What it catches |
|---|---|---|
z.string().trim().pipe(z.email()) | Bad format and stray spaces from autofill | |
| Quantity | z.coerce.number().int().min(1) | "abc", 1.5 and an empty field, which becomes 0 |
| Postal code | z.string().regex(/^\d{5}$/) | Letters and wrong length; keeps the leading zero |
| Shipping method | z.enum(["standard", "express"]) | Options that are not on your list |
| Checkbox | z.literal("on").optional() | Checked sends "on"; unchecked sends nothing. Avoid z.coerce.boolean(): it turns "false" into true |
| Link | z.httpUrl() | Only http and https. z.url() accepted javascript:alert(1) in our test |
| Price or total | None | Never take it from the client: read it from your database |
Scroll the figure sideways to see all of it
Use it in the form
In the browser, the schema checks the data before it is sent, so the error shows next to the field without a round trip. The function takes a FormData, so it does not depend on React and runs in Node for tests:
// lib/check-order.ts
import * as z from "zod";
import { OrderInput } from "@/lib/order-schema";
// Runs in the browser before anything is sent: same schema as the API.
// Returns the clean order, or the messages for each field.
export function checkOrder(data: FormData) {
const result = OrderInput.safeParse(Object.fromEntries(data));
if (!result.success) {
return { ok: false as const, errors: z.flattenError(result.error).fieldErrors };
}
return { ok: true as const, order: result.data };
}
Object.fromEntries(data)turns theFormDatainto an object of strings, such as{ quantity: "2" }. Everything arrives as text, which is why quantity usesz.coerce.safeParsenever throws: it returns{ success: true, data }or{ success: false, error }, as the zod basics page explains.parsethrows aZodErrorinstead.- On failure,
z.flattenErrorgroups the messages by field:{ email: ["Check your email address"] }. - On success, it returns
result.data: strings already trimmed and quantity as a number.
The component wires that function to the form and to the API:
// components/OrderForm.tsx
"use client";
import { useState } from "react";
import { checkOrder } from "@/lib/check-order";
export function OrderForm() {
const [errors, setErrors] = useState<Record<string, string[] | undefined>>({});
async function onSubmit(event: React.FormEvent<HTMLFormElement>) {
event.preventDefault();
const checked = checkOrder(new FormData(event.currentTarget));
if (!checked.ok) return setErrors(checked.errors);
const res = await fetch("/api/orders", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(checked.order),
});
setErrors(res.status === 400 ? (await res.json()).fieldErrors : {});
}
return (
<form onSubmit={onSubmit} noValidate>
<label htmlFor="email">Email</label>
<input id="email" name="email" type="email" autoComplete="email"
aria-invalid={Boolean(errors.email)} aria-describedby="email-error" />
<p id="email-error">{errors.email?.[0]}</p>
{/* name, postalCode, quantity and notes repeat the same pattern */}
<button type="submit">Place order</button>
</form>
);
}
noValidateturns off the browser's own bubbles so messages come from one place: the schema.- In
onSubmit,checkOrderchecks the form. If there are errors, they go into state and nothing is sent. - If it passes,
checked.orderis sent as JSON. If the server answers 400, itsfieldErrorsare shown; they have the same shape as the browser's. - The field links its message with
aria-describedbyand setsaria-invalid, so a screen reader announces it.
One note on weight: import the schema into a "use client" component and zod ships to the browser. In our zod 3 test that was 12.8 kB gzipped, measured in where to put the use client boundary. If size matters, zod 4 includes Zod Mini (zod/mini), a functional variant built to tree-shake better.
Scroll the figure sideways to see all of it
Use it in the API route: reject with 400
The API route is the door nobody can skip. In the Next.js App Router it is a route.ts with standard Request and Response:
// app/api/orders/route.ts
import * as z from "zod";
import { OrderInput } from "@/lib/order-schema";
export async function POST(request: Request) {
const body: unknown = await request.json().catch(() => null);
const result = OrderInput.safeParse(body);
if (!result.success) {
return Response.json(z.flattenError(result.error), { status: 400 });
}
const order = result.data; // OrderInput: trimmed, typed, unknown keys dropped
// Save the order here. Price and stock come from your database, not from the body.
return Response.json({ ok: true, quantity: order.quantity }, { status: 201 });
}
request.json()throws when the body is not valid JSON..catch(() => null)turns that intonull, which the schema rejects like any other bad input.bodyisunknown, notany: TypeScript will not let you use it until it has gone through the schema.- On failure, it answers 400 with
z.flattenError:formErrorsfor problems with the whole object andfieldErrorsper field. - On success,
result.datais anOrderInput. An extrapricefield we sent never arrives:z.objectstrips it. - Price and stock come from your database, never from the request body.
These are the three responses the route gave when we called it with Request objects on Node 22:
// valid, with an extra "price": 0
201 {"ok":true,"quantity":2}
// bad email and 50 units
400 {"formErrors":[],"fieldErrors":{"email":["Check your email address"],"quantity":["Up to 10 per order"]}}
// body that is not JSON
400 {"formErrors":["Invalid input: expected object, received null"],"fieldErrors":{}}
A 400 (Bad Request) tells the caller the problem is in what they sent and that repeating the same request will not help. With parse and no try, the exception would surface as a 500, which says the opposite: that your server broke. Stopping duplicate orders from retries is a separate problem, solved with an idempotency key.
The same door works for other inputs. When an AI model calls one of your functions, the arguments arrive as JSON you did not write: check them against a schema before they touch the cart, as in function calling explained with a shopping cart. And when you ask a model for reliable JSON with structured outputs, zod checks what the JSON schema does not guarantee.
z.infer for the type
Without zod you would write an interface by hand and a validator next to it, and sooner or later they would disagree. With z.infer, the type comes from the schema: add a field and TypeScript flags every place that does not handle it.
type OrderInput = z.infer<typeof OrderInput>;
// { name: string; email: string; postalCode: string;
// quantity: number; notes?: string | undefined }
type OrderFormValues = z.input<typeof OrderInput>;
// the same, but quantity: unknown, because z.coerce accepts any input
z.infergives the output type: what you hold after validation. It is the same asz.output.z.inputgives the input type. Withz.coercethe input isunknown;.transform()also makes the two types differ.- We confirmed both types with a type-equality check under
tsc --strict.
Use the output type for everything past the door: the function that saves the order, the confirmation email, the shipping calculation. None of them takes unknown or validates again.
Error messages people can act on
The default messages are in English and read like a developer wrote them: Too small: expected number to be >=1. Zod 4 ships translations too; we tried z.config(z.locales.es()) for a Spanish store and got stiff, literal strings. Fine for a log, not for a shopper.
The practical fix is a message on each rule. Per the error customization page, nearly every zod API takes a string, or an object like { error: "..." }, and a rule's message wins over the schema's. That is why, in the schema above, "abc" gives Enter a number and "1.5" gives Whole units only.
To display them, the error formatting page describes three functions:
z.flattenError: messages per field, for flat forms like this one.z.treeifyError: a tree oferrorsandproperties, for nested objects.z.prettifyError: a readable string, for logs:
✖ Check your email address
→ at email
✖ Up to 10 per order
→ at quantity
A good message says what to do, not what failed: "A postal code has 5 digits" instead of "Invalid string". Show each message next to its field, not in a list above the form, and never show error.message as is: it is a JSON dump of every issue at once.
Common mistakes
- Validating only in the browser. Anyone can call the API without the form. The server always validates.
- Writing
as OrderInputinstead of using the schema. A cast checks nothing; it only silences the compiler. parsewithouttryin a route. The exception ends as a 500. UsesafeParseand answer 400.- Expecting
undefinedfrom an empty field.FormDatasends"":.optional()lets it through andz.coerce.number()turns it into 0. z.coerce.boolean()for a checkbox. Any non-empty string istrue,"false"included.z.email().trim(). The format is checked before the trim; trim first and use.pipe().z.url()for links you will render. It acceptsjavascript:; usez.httpUrl().- A hand-written
interfacenext to the schema. They drift. Derive the type withz.infer.
Frequently asked questions
Should I use zod 3 or zod 4?
Zod 4 for new code: it has been stable since July 2025, and 4.6.7 is the latest on npm as of November 19, 2026. If your project is still on 3.25.x, that package also ships zod 4 under "zod/v4", so you can migrate one file at a time.
parse or safeParse?
safeParse at entry points, where bad input is normal and you want to answer with a 400 and the messages. parse fits places where bad data is your own bug, such as reading configuration at startup: there you want the program to stop.
If the form already validates, do I need server validation?
Yes. Browser validation is there so people can fix mistakes fast; server validation is what protects your data. With one schema you write nothing twice: both import the same file.
How do I reject fields I do not expect?
z.object strips them without an error, which is enough to store clean data. If you would rather reject the request, use z.strictObject: with an extra price it returned Unrecognized key: "price".
Checklist
- Every entry point (form, API, outside service) goes through a schema, once.
- The schema lives in one file that both the form and the API route import.
- The route uses
safeParseand answers 400 withz.flattenError. - The body is read as
unknown, and malformed JSON also gets a 400. - Types come from
z.infer, with no hand-writteninterfaceand noas. - Strings are trimmed before the format check.
- Every rule has a message that says what to do, shown next to its field.
- Price, stock and totals come from the server, never from the body.
With one door, the rest of your code stops doubting its data. Next, make the form easy to fill in on a phone: review the autocomplete and keyboard for every field.
So that a screen reader also announces those error messages, see accessible forms under WCAG 2.2.
Saw this on Instagram? Every Reel guide is at ecomlabs.dev/guides.
Written by

Published November 19, 2026 · updated November 20, 2026