Skip to content

Volume ITechnology

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:

SourceWho controls itWhat can go wrong
A server replyAnother team, or a third partyFields renamed, missing, or a different type
The URL and search paramsThe user, who can type anything?page=banana
Form fieldsThe userEmpty, too long, wrong format
localStorageAn older version of your app, or the userOld 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.

Outside: not trustedServer reply (JSON)URL and search paramsForm fieldslocalStorageEnvironment valuesZod schemasafeParse(data)checks every fieldand its typeInside: trusteddata has a real typeProduct, Order, Searchno more "as" guessesStopped at the gateerror with the fieldpath and a messageshow it, log itvalidinvalidThe type system checks your code. The schema checks the world.
A schema is a gate at the edge of your app. Everything from outside arrives as unknown. The schema checks it. Good data goes through with a real type. Bad data is stopped there, with a clear error, instead of breaking a screen somewhere else.

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 zod

This 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)
  1. z.object({...}) describes an object. Each key is a field, and each value says what that field must be.
  2. 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.
  3. z.int() is a whole number. .nonnegative() means zero or more. A price of 19.99 would be rejected, because we store cents as whole numbers.
  4. 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 a type Product by 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)
}
  1. When success is true, result.data holds the checked value, and TypeScript knows its type is Product.
  2. When it is false, result.error.issues is 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 wantWriteNotes
Textz.string()add .min(3), .max(50), .trim()
An emailz.email()message: Invalid email address
A whole numberz.int()1.5 fails
Any numberz.number()add .min(0), .max(100)
True or falsez.boolean()
One of a fixed setz.enum(['PT', 'DE'])the type becomes 'PT' | 'DE'
An exact valuez.literal('shop')
A listz.array(productSchema)
A date from textz.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 field

We 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)
  })
  1. refine takes a function that returns true when the value is fine. It receives the whole object, so it can compare fields.
  2. path says which field the error belongs to. Without it, the error would belong to the object as a whole and no field would show it.
  3. The message. (In Zod 3 this option was called message. In Zod 4, error is 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   // false

A 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' }
  1. '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 got Invalid discriminator value. Expected 'added' | 'cleared'. And in your code, after if (event.type === 'added'), TypeScript knows event.productId exists. This is the same "discriminated union" you used for LoadState on 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)
}
  1. The function takes any schema, and its return type is whatever that schema describes. One function works for products, orders and everything else.
  2. We type the result as unknown, on purpose. It is the honest type. Nothing is assumed.
  3. 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 priceCents story.
  4. 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 a ZodError. error.issues lists every problem with a path, code and message.
  • Unknown keys are stripped (z.strictObject rejects 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 with safeParseAsync.
  • .transform(fn) changes the value. Input and output types can differ (z.input vs z.infer).
  • z.coerce.number() turns text to a number. Number('') is 0, so an empty field passes. Guard with z.string().min(1).pipe(z.coerce.number()).
  • Where: API replies (getValidated(url, schema) instead of as T), search params (.catch(undefined)), forms, storage.
  • Form errors: z.flattenError(error).fieldErrors gives { 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.

Combine chapters into one PDF

Pick the chapters you want. They print in the order you pick them.

Volume I — Technology
Part 0 — Retention & Notation
Part 1 — Foundations of Computation
Part 2 — Operating Systems
2.1 The Kernel
2.2 Processes
2.3 Threads & Scheduling
2.4 Concurrency Under the Hood
2.5 Memory Management
2.6 File Systems
2.7 Input/Output
2.8 Linux for Engineers
2.9 Windows & macOS in Practice
Part 3 — Languages, Compilers & Runtimes
3.6 JavaScript & V8
3.7 TypeScript
3.8 Node.js Internals
3.13 Python & CPython
3.14 FastAPI & Production Python
Part 4 — Data Structures & Algorithms
4.0 Classic Problems — Before NeetCode
4.4 Arrays & Hashing — Problems
4.5 Two Pointers
4.6 Sliding Window
4.8 Stack — Problems
4.9 Linked List — Problems
4.11 Binary Search — Problems
4.13 Trees
4.14 Tree — Problems
4.15 Trie — Problems
4.17 Heap — Problems
4.18 Backtracking — Problems
4.19 Graphs
4.20 Graph — Problems
4.21 Advanced Graph — Problems
4.23 1-D DP — Problems
4.24 2-D DP — Problems
4.26 Greedy — Problems
4.27 Interval — Problems
4.28 Math & Geometry — Problems
4.30 Bit Manipulation — Problems
Part 5 — Networking & the Web
5.3 IP
5.4 Transport
5.6 HTTP
Part 6 — Frontend Engineering
6.1 Browser Internals
6.2 HTML & CSS Mastery
6.3 JavaScript in the Browser
6.4 React, from First Component to Full Shop
6.5 Frameworks & Rendering
6.8 UI Engineering & Patterns
Part 7 — Databases & Storage
7.2 SQL Mastery
7.3 Storage Engine Internals
7.4 Transactions
7.5 NoSQL Taxonomy
7.8 Analytics & Big Data
Part 8 — Security, Identity & Cryptography
8.2 Cryptography
8.3 Protocols of Trust
8.4 Identity: AuthN & AuthZ
8.5 Application Security
8.6 Infrastructure Security
Part 9 — Software Design (LLD)
9.2 OOP Foundations
9.3 Design Principles
9.4 Design Patterns
9.5 Concurrency
9.6 API Design
9.7 LLD Interview Machines
9.9 Node/Express Production Playbook
Part 10 — Distributed Systems & HLD
10.7 Consistency & Consensus
10.8 Messaging & Microservices
10.14 Caching
Building blocks from the design seat
Part 11 — System Design Case Studies
Part 12 — AI & ML Engineering
12.1 What AI Engineering Is
12.2 The Math You Need
12.3 Classical Machine Learning
12.4 Data for ML
12.5 Deep Learning
12.6 Embeddings & Vector Search
12.7 Transformers & LLMs
12.8 Building with LLMs
12.9 Retrieval-Augmented Generation
12.10 Agents
12.11 Adapting Models
12.12 Production AI
12.13 Multimodal AI
12.14 AI Security & Governance
12.15 Case Studies & Capstone
Part 13 — Cloud, DevOps & Infrastructure
13.11 Git, from First Commit to Team Workflow
Part 14 — Containers: Docker & Kubernetes
14.1 Foundations
14.2 Docker
14.3 Kubernetes
14.4 Kubernetes on Azure
Part 15 — The Craft & Career
Nothing picked yet