Skip to content

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)
  1. Zod validation: check once, at the door
  2. Define the schema
  3. Use it in the form
  4. Use it in the API route: reject with 400
  5. z.infer for the type
  6. Error messages people can act on
  7. Common mistakes
  8. Frequently asked questions
  9. Checklist

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.

one door: the schema checks everything that comes incomes inschemayour code getssafeParseOrderInputname: " Ana "name: "Ana"email: " ana@x.com "email: "ana@x.com"quantity: "2"quantity: 2quantity: "abc"bounced with 400price: 0droppedthe browser helps; the server decidesvalidate once, at the doorpast the door, everything is an OrderInput

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>;
  1. import * as z from "zod" is the import the zod 4 docs use.
  2. z.object defines the object. By default, keys that are not in the schema are stripped from the result without an error, per the API reference.
  3. name: .trim() removes whitespace before the length check, and .min(2, "...") requires two characters with a custom message.
  4. email: trims first, then .pipe() hands the clean string to z.email(). Order matters: we tried z.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.
  5. postalCode: five digits with .regex(). It stays a string so the leading zero in 06700 survives.
  6. quantity: z.coerce.number() converts the form's string with Number(input). Its message is used when the result is not a number. Then .int(), .min(1) and .max(10), each with its own message.
  7. notes: optional, 500 characters at most.
  8. z.infer derives the type from the schema. Type and schema share the name OrderInput: 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:

FieldSchemaWhat it catches
Emailz.string().trim().pipe(z.email())Bad format and stray spaces from autofill
Quantityz.coerce.number().int().min(1)"abc", 1.5 and an empty field, which becomes 0
Postal codez.string().regex(/^\d{5}$/)Letters and wrong length; keeps the leading zero
Shipping methodz.enum(["standard", "express"])Options that are not on your list
Checkboxz.literal("on").optional()Checked sends "on"; unchecked sends nothing. Avoid z.coerce.boolean(): it turns "false" into true
Linkz.httpUrl()Only http and https. z.url() accepted javascript:alert(1) in our test
Price or totalNoneNever take it from the client: read it from your database
common validations for a store formfieldzodwhat it catchesemailz.string().trim().pipe(z.email())format, stray spacesquantityz.coerce.number().int().min(1)"abc", 1.5 and "" (becomes 0)postal codez.string().regex(/^\d{5}$/)letters, length; keeps the 0shippingz.enum(["standard", "express"])options that do not existcheckboxz.literal("on").optional()not coerce.boolean: "false" is truelinkz.httpUrl()z.url() lets javascript: throughprice is not validated: read it from your databasezod validation at the doortested with zod 4.6.7 on Node 22, November 2026

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 };
}
  1. Object.fromEntries(data) turns the FormData into an object of strings, such as { quantity: "2" }. Everything arrives as text, which is why quantity uses z.coerce.
  2. safeParse never throws: it returns { success: true, data } or { success: false, error }, as the zod basics page explains. parse throws a ZodError instead.
  3. On failure, z.flattenError groups the messages by field: { email: ["Check your email address"] }.
  4. 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>
  );
}
  1. noValidate turns off the browser's own bubbles so messages come from one place: the schema.
  2. In onSubmit, checkOrder checks the form. If there are errors, they go into state and nothing is sent.
  3. If it passes, checked.order is sent as JSON. If the server answers 400, its fieldErrors are shown; they have the same shape as the browser's.
  4. The field links its message with aria-describedby and sets aria-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.

one schema, three useslib/order-schema.tsz.object({ … })formcheckOrder(formData)error next to the fieldAPIsafeParse(body)invalid → 400typez.infer<typeof OrderInput>no hand-written interfacechange the schema, all three followsame messages in the browser and on the server

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 });
}
  1. request.json() throws when the body is not valid JSON. .catch(() => null) turns that into null, which the schema rejects like any other bad input.
  2. body is unknown, not any: TypeScript will not let you use it until it has gone through the schema.
  3. On failure, it answers 400 with z.flattenError: formErrors for problems with the whole object and fieldErrors per field.
  4. On success, result.data is an OrderInput. An extra price field we sent never arrives: z.object strips it.
  5. 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
  1. z.infer gives the output type: what you hold after validation. It is the same as z.output.
  2. z.input gives the input type. With z.coerce the input is unknown; .transform() also makes the two types differ.
  3. 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 of errors and properties, 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 OrderInput instead of using the schema. A cast checks nothing; it only silences the compiler.
  • parse without try in a route. The exception ends as a 500. Use safeParse and answer 400.
  • Expecting undefined from an empty field. FormData sends "": .optional() lets it through and z.coerce.number() turns it into 0.
  • z.coerce.boolean() for a checkbox. Any non-empty string is true, "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 accepts javascript:; use z.httpUrl().
  • A hand-written interface next to the schema. They drift. Derive the type with z.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 safeParse and answers 400 with z.flattenError.
  • The body is read as unknown, and malformed JSON also gets a 400.
  • Types come from z.infer, with no hand-written interface and no as.
  • 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

Luis Morales

Luis Morales

Frontend and Shopify developer, EcomLabs

@luismoralesdev on Instagram

Published November 19, 2026 · updated November 20, 2026

← Blog