Appearance
6.4.13 — Zod: Trusting Data You Did Not Create
Your shop loads products from a server. On page 6.4.10 the query function ended with return (await res.json()) as T. That as T is you telling TypeScript: "trust me, the data looks like T".
Now the backend team renames priceCents to price. Nobody tells the front end. TypeScript is perfectly happy, because it was only ever told to trust. The page now shows $NaN for every product, and the bug report says "prices are broken", with no hint about where.
TypeScript checks your code while you build it. It cannot check data that arrives while the app runs. Zod is a small library that does that second job. You describe what the data must look like. Zod checks the real data against the description, and tells you exactly what is wrong.
1. Why TypeScript types are not enough
TypeScript types disappear when your code is built. The browser never sees them. So when data comes from outside, TypeScript has no way to know what it really is. Look at where data comes from in a real app:
| Source | Who controls it | What can go wrong |
|---|---|---|
| A server reply | Another team, or a third party | Fields renamed, missing, or a different type |
| The URL and search params | The user, who can type anything | ?page=banana |
| Form fields | The user | Empty, too long, wrong format |
localStorage | An older version of your app, or the user | Old shape, or edited by hand |
All of these arrive as text or unknown values. You must check them. You could write the checks by hand: typeof data.price === 'number', and so on, for every field, in every place. That is long, easy to get wrong, and the result is still not connected to your TypeScript types. Zod writes the checks from a short description, and gives you the type for free.
Look at the picture. Everything from outside the app (left) is treated as untrusted. It goes through a schema at the edge. Valid data comes out the other side with a real type. Invalid data is stopped right there with a clear message, instead of causing a strange failure three screens later.
2. Your first schema
bash
npm install zodThis page uses Zod 4. A schema is a description of what a value must look like.
ts
// src/schemas/product.ts
import { z } from 'zod'
export const productSchema = z.object({ // (1)
id: z.string(),
name: z.string().min(1), // (2)
priceCents: z.int().nonnegative(), // (3)
inStock: z.boolean(),
})
export type Product = z.infer<typeof productSchema> // (4)z.object({...})describes an object. Each key is a field, and each value says what that field must be.z.string()means "a string"..min(1)adds a rule: at least one character, so the name cannot be empty. Rules chain onto the type.z.int()is a whole number..nonnegative()means zero or more. A price of19.99would be rejected, because we store cents as whole numbers.z.infer<typeof productSchema>gives you the TypeScript type that the schema describes. You write the shape once, as a schema. The type is worked out from it. Now the type and the check can never disagree. (Compare with the usual way, where you write atype Productby hand and a separate check somewhere else, and they drift apart.)
The type that z.infer produced is exactly:
ts
type Product = { id: string; name: string; priceCents: number; inStock: boolean }Checking data: safeParse
Parsing means "check this value against the schema, and give me back the checked value".
ts
const result = productSchema.safeParse({
id: 'p1', name: 'Red mug', priceCents: 1999, inStock: true,
})
if (result.success) {
console.log(result.data.name) // (1)
} else {
console.log(result.error.issues) // (2)
}- When
successistrue,result.dataholds the checked value, and TypeScript knows its type isProduct. - When it is
false,result.error.issuesis a list of everything that was wrong.
safeParse never throws. It always returns an object with a success flag. There is also parse, which returns the value directly but throws a ZodError if the data is bad. Use safeParse when you want to handle bad data (a form, a search param). Use parse when bad data is a bug you want to crash on.
What an error looks like
We ran the schema against data with three mistakes: an empty name, a price of 19.99, and 'yes' where a boolean belongs:
ts
productSchema.safeParse({ id: 'p1', name: '', priceCents: 19.99, inStock: 'yes' })The three issues Zod returned, in the order of the fields:
text
path: ['name'] code: 'too_small' message: 'Too small: expected string to have >=1 characters'
path: ['priceCents'] code: 'invalid_type' message: 'Invalid input: expected int, received number'
path: ['inStock'] code: 'invalid_type' message: 'Invalid input: expected boolean, received string'Each issue tells you where (path), what kind of problem (code), and a readable message. Zod reports all the problems at once, not only the first. For nested data the path goes deeper: a bad price inside the first item of a list had the path ['items', 0, 'priceCents'].
Unknown keys are removed
If the data has extra fields that the schema does not mention, Zod leaves them out of the result. We passed { ..., evil: 'x' } and got back an object without evil. This is a quiet safety benefit: only what you declared gets through. If you would rather get an error for extra keys, use z.strictObject({...}). We checked, and it reports unrecognized_keys.
3. The building blocks
You can describe almost anything with a few parts. Each of these was run to confirm the behavior shown.
| You want | Write | Notes |
|---|---|---|
| Text | z.string() | add .min(3), .max(50), .trim() |
| An email | z.email() | message: Invalid email address |
| A whole number | z.int() | 1.5 fails |
| Any number | z.number() | add .min(0), .max(100) |
| True or false | z.boolean() | |
| One of a fixed set | z.enum(['PT', 'DE']) | the type becomes 'PT' | 'DE' |
| An exact value | z.literal('shop') | |
| A list | z.array(productSchema) | |
| A date from text | z.iso.datetime() | checks 2026-10-28T10:00:00Z |
| Maybe missing | .optional() | string | undefined |
Maybe null | .nullable() | string | null |
| A default | .default(1) | used when the value is missing |
optional, nullable and default are easy to mix up:
ts
z.string().optional().safeParse(undefined).success // true (missing is allowed)
z.string().nullable().safeParse(null).success // true (null is allowed)
z.string().safeParse(undefined).success // false (required by default)
z.object({ qty: z.number().default(1) }).parse({}) // { qty: 1 } (filled in)Everything is required unless you say otherwise. This is the safe direction. A field you forget to mark optional is an error, which you notice, instead of a silent undefined.
Reshaping a schema
You rarely need an exact copy of a schema. Zod can derive new ones:
ts
const productSummary = productSchema.pick({ name: true, priceCents: true }) // only these two fields
const productPatch = productSchema.partial() // every field optional
const productWithTags = productSchema.extend({ tags: z.array(z.string()).default([]) }) // one more fieldWe checked all three: pick keeps two keys, partial accepts {}, and extend fills tags: [] when it is missing. This is how one base schema gives you the "create" form (without id), the "edit" form (everything optional) and the "show" type, without writing the fields three times.
4. Your own rules: refine
The built-in rules cover one field at a time. Some rules involve several fields. The classic one is "password and confirmation must match".
ts
const signupSchema = z
.object({
password: z.string().min(8, 'Use at least 8 characters'),
confirm: z.string(),
})
.refine((values) => values.password === values.confirm, { // (1)
path: ['confirm'], // (2)
error: 'Passwords do not match', // (3)
})refinetakes a function that returnstruewhen the value is fine. It receives the whole object, so it can compare fields.pathsays which field the error belongs to. Without it, the error would belong to the object as a whole and no field would show it.- The message. (In Zod 3 this option was called
message. In Zod 4,erroris the main name. Both still work.)
We tested it with 12345678 and 1234567: one issue, on the path ['confirm'], with the message Passwords do not match.
Also, a rule can be asynchronous, for example "is this username free?". Use an async function in refine and call safeParseAsync. We checked that it returns success: false for a name the function rejects.
5. Changing the value while parsing: transform and coerce
transform
A schema can clean the value on its way through:
ts
const emailField = z.string().transform((s) => s.trim().toLowerCase())
emailField.parse(' Ana@Example.COM ') // 'ana@example.com'The input was messy and the output is tidy. Notice that this means the input type and the output type of a schema can differ. z.infer gives the output type. If you need the input type, use z.input<typeof schema>.
coerce: turning text into a number
Form fields and URL params are always text. An age field gives "21", not 21. z.coerce.number() converts first, then checks:
ts
const ageField = z.coerce.number().int().min(18, 'Must be 18 or older')
ageField.safeParse('21').data // 21
ageField.safeParse('17').success // falseA trap that surprises everyone: coercion uses JavaScript's own Number(...), and Number('') is 0. So an empty field becomes 0 and passes. We checked: z.coerce.number().safeParse('') gives 0, and z.coerce.number().min(18) would only fail because 0 is under 18, not because the field is empty. If "empty" must be an error, check for it first:
ts
const ageField = z
.string()
.min(1, 'Enter your age') // empty text is an error
.pipe(z.coerce.number().int().min(18, 'Must be 18 or older')).pipe(...) means "take the result of the first schema and feed it to the second". The first step rejects empty text. The second turns the text into a number and checks it.
6. One of several shapes: unions
Sometimes data can have different shapes, and a field says which one. Think of an event log for the cart:
ts
const cartEventSchema = z.discriminatedUnion('type', [ // (1)
z.object({ type: z.literal('added'), productId: z.string() }),
z.object({ type: z.literal('cleared') }),
])
type CartEvent = z.infer<typeof cartEventSchema>
// { type: 'added'; productId: string } | { type: 'cleared' }'type'names the field that tells the shapes apart (the discriminator). Zod looks at it first and checks only the matching shape. That gives a precise error: for{ type: 'zzz' }we gotInvalid discriminator value. Expected 'added' | 'cleared'. And in your code, afterif (event.type === 'added'), TypeScript knowsevent.productIdexists. This is the same "discriminated union" you used forLoadStateon page 6.4.3.
7. Where to put the gate in a real app
Server replies
This replaces the as T from page 6.4.10. We write one function that fetches, checks, and returns a typed value:
ts
// src/api/client.ts
import { z } from 'zod'
export async function getValidated<S extends z.ZodType>(
url: string,
schema: S,
signal?: AbortSignal,
): Promise<z.infer<S>> { // (1)
const res = await fetch(url, { signal })
if (!res.ok) throw new Error(`The server answered ${res.status}`)
const json: unknown = await res.json() // (2)
const parsed = schema.safeParse(json)
if (!parsed.success) {
const first = parsed.error.issues[0] // (3)
throw new Error(`The server sent unexpected data at "${first?.path.join('.')}": ${first?.message}`)
}
return parsed.data // (4)
}- The function takes any schema, and its return type is whatever that schema describes. One function works for products, orders and everything else.
- We type the result as
unknown, on purpose. It is the honest type. Nothing is assumed. - If the data does not match, we throw an error that names the field path and the problem. This is the message that would have saved you in the
priceCentsstory. - Only data that passed the check gets out, and TypeScript knows its type exactly.
Using it with a query from page 6.4.10:
tsx
// src/api/products.ts
import { queryOptions } from '@tanstack/react-query'
import { z } from 'zod'
import { getValidated } from './client'
import { productSchema } from '../schemas/product'
export const productListOptions = () =>
queryOptions({
queryKey: ['products', 'list'],
queryFn: ({ signal }) => getValidated('/api/products', z.array(productSchema), signal),
})Now if the server renames priceCents to price, the query fails with the message The server sent unexpected data at "0.priceCents": Invalid input: expected number, received undefined. The failing screen shows its error state, TanStack Query reports it, and the problem is found in minutes instead of days. We tested this with a reply that had price and the first issue came back with exactly that path.
URL search params
Page 6.4.12 wrote validateSearch by hand. With Zod it is shorter, and the router accepts a schema directly:
ts
const searchSchema = z.object({
q: z.string().optional().catch(undefined),
sort: z.enum(['name', 'price']).optional().catch(undefined),
}).catch(undefined) means "if this field is wrong, use undefined instead of failing". A user who types ?sort=banana still sees a working page. (The word catch here belongs to Zod, it has nothing to do with try/catch.)
Forms
A form is the third boundary. The next page (6.4.14) connects a Zod schema to a form library, so the same schema validates the fields and gives the form its types.
Extracting error messages for a form
Zod 4 provides helpers that turn the list of issues into something a form can use. Here is a signup attempt with a bad email, an age of 17, and an unknown country:
ts
const form = z.object({
email: z.email('Enter a valid email'),
age: z.coerce.number().int().min(18, 'Must be 18 or older'),
country: z.enum(['PT', 'DE']),
})
const result = form.safeParse({ email: 'nope', age: '17', country: 'FR' })
if (!result.success) {
const errors = z.flattenError(result.error).fieldErrors
}errors is:
text
{
email: ['Enter a valid email'],
age: ['Must be 18 or older'],
country: ['Invalid option: expected one of "PT"|"DE"']
}One entry per field, each a list of messages. That is the shape a form wants. For deeply nested data, z.treeifyError(error) keeps the nesting.
8. What Zod does not do
- It is a runtime check. It costs a little time for each parse. Use it at the edges (network, forms, URLs), not on data you have already checked, and not in a tight loop over a million items.
- It does not check business rules that need a database, such as "does this email already have an account". That belongs on the server. Zod can run the same shape check on the server too, which is a real strength: one schema file that both sides share.
- It does not secure anything by itself. A front-end check is a convenience for the user. The server must always check again, because anyone can send requests without your page.
What the interviewer will push on
"Why use Zod when you already have TypeScript?" TypeScript types exist only at build time. Data from a server, a URL, a form or storage arrives at runtime and is unchecked. Zod validates it at runtime and, with z.infer, produces the type from the same definition, so they cannot drift apart.
"parse vs safeParse?" parse returns the value or throws a ZodError. safeParse returns { success, data } or { success: false, error }. Use safeParse where you want to handle bad input, such as in forms.
"What does z.infer give you, and why does it matter?" The TypeScript type of a schema's output. It means one source of truth: change the schema and the type changes. Mention z.input for when a transform or coerce makes input and output differ.
"How do you validate that two fields match?" refine on the object schema, with path set to the field that should show the error.
"A form field age arrives as ''. What does z.coerce.number() do?" It gives 0, because Number('') is 0, so the empty field passes. Check for empty text first with z.string().min(1).pipe(z.coerce.number()). This question separates people who have used it from people who have read about it.
"Where do you apply Zod in a frontend?" At every boundary: API responses (so as is never needed), URL search params, form values, and persisted storage.
One thing to volunteer: say that the front-end validation is for user experience and the server must validate again, ideally with the same schema file shared between both.
Recall
- TypeScript types vanish at runtime. Data from a server, URL, form or storage is untrusted. A schema is a runtime check, placed at the edge.
z.object({ field: z.string().min(1), ... })describes the shape.type T = z.infer<typeof schema>derives the TypeScript type: write the shape once.safeParse(x)returns{ success: true, data }or{ success: false, error }and never throws.parse(x)returns the data or throws aZodError.error.issueslists every problem with apath,codeandmessage.- Unknown keys are stripped (
z.strictObjectrejects them). Everything is required unless.optional()(undefined),.nullable()(null) or.default(v). - Reshape:
.pick,.omit,.partial,.extend. Lists:z.array(s). Choices:z.enum([...]),z.literal(v),z.discriminatedUnion('type', [...]). .refine(fn, { path, error })for rules across fields (password match). Async rules work withsafeParseAsync..transform(fn)changes the value. Input and output types can differ (z.inputvsz.infer).z.coerce.number()turns text to a number.Number('')is 0, so an empty field passes. Guard withz.string().min(1).pipe(z.coerce.number()).- Where: API replies (
getValidated(url, schema)instead ofas T), search params (.catch(undefined)), forms, storage. - Form errors:
z.flattenError(error).fieldErrorsgives{ field: [messages] }. - Zod is a runtime check for user experience. The server must check again.
Self-test: Why is as Product[] on a server reply risky? · What is the difference between safeParse and parse? · How does z.infer stop a type and a check from drifting apart? · Why does an empty text field pass z.coerce.number()? · What does path do in refine?
Next: 6.4.14 connects Zod to React Hook Form, the library that builds forms with very little state and very few re-renders, using the same schema for validation and for types.