Full answer
Why validate
- Anything from outside (HTTP bodies, query strings, environment variables, queue messages, files) can have the wrong shape. Type annotations are removed at run time and protect nothing.
- Validation prevents crashes, bad data in the database, and some injection and mass-assignment problems. It also gives users useful errors.
How zod works
- Build a schema: z.object({ name: z.string().min(1), age: z.int().min(0), email: z.email() }).
- schema.parse(input) returns the typed, cleaned value or throws a ZodError.
- schema.safeParse(input) returns { success: true, data } or { success: false, error }. Use it when invalid input is normal, such as in request handlers.
- error.issues lists each problem with path, code and message.
- By default unknown keys are removed (stripped). z.strictObject rejects them.
- optional(), nullable(), default(value) and enum for fixed choices.
- Coercion: z.coerce.number() turns '42' into 42, which is useful for query strings and environment variables. Be careful with coerce.boolean, because any non-empty string is true. Use explicit enums or transforms.
- transform and refine add conversion and custom rules. Keep them small and pure.
- z.infer<typeof schema> gives the TypeScript type from the schema (one source of truth).
Good practice
- Validate once at the boundary, then pass the parsed value on.
- Return messages that do not leak internals. Do not echo secrets.
- Put a size limit on the body before parsing, because validation does not limit memory.
- Alternatives: ajv with JSON Schema (used by Fastify), valibot, joi, yup.
javascript
const { z } = require('zod');
const Student = z.object({
name: z.string().trim().min(1),
age: z.coerce.number().int().min(5).max(100),
email: z.email(),
track: z.enum(['web', 'data']).default('web'),
});
// Valid input with strings that need conversion, an extra key and a missing default.
const ok = Student.safeParse({ name: ' Asha ', age: '17', email: 'asha@example.com', admin: true });
console.log('ok:', ok.success, JSON.stringify(ok.data));
// Invalid input: every problem is reported.
const bad = Student.safeParse({ name: '', age: 'abc', email: 'not-an-email', track: 'art' });
console.log('success:', bad.success);
for (const issue of bad.error.issues) console.log(' -', issue.path.join('.'), '|', issue.code);
// parse throws
try { Student.parse(null); } catch (err) { console.log('parse threw', err.name, 'with', err.issues.length, 'issue'); }
// A strict object rejects unknown keys instead of removing them.
const Strict = z.strictObject({ name: z.string() });
console.log('strict with extra key:', Strict.safeParse({ name: 'Asha', admin: true }).error.issues[0].code);
// A classic coerce trap
console.log('coerce.boolean("false") =', z.coerce.boolean().parse('false'));A schema converts and checks a good input, reports each problem of a bad input, and shows the strict and coerce behaviour. Install first with npm install zod (run here with zod 4.6.7). Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): ok: true {"name":"Asha","age":17,"email":"asha@example.com","track":"web"} success: false - name | too_small - age | invalid_type - email | invalid_format - track | invalid_value parse threw ZodError with 1 issue strict with extra key: unrecognized_keys coerce.boolean("false") = true
Key points
- Types do not exist at run time, so validate untrusted input.
- parse throws, safeParse returns a result.
- issues give a path and a message for each error.
- Objects strip unknown keys by default.
- coerce converts strings, but coerce.boolean is risky.
Common mistakes
- Trusting TypeScript types for data from the network.
- Using z.coerce.boolean on strings such as 'false'.
- Validating in some routes but not others.
- Returning raw internal error text to clients.
- Parsing a huge body without a size limit.
Follow-ups
- How do you get a TypeScript type from a zod schema?
- What is the difference between strip and strict objects?
- How would you validate environment variables with zod?
Tips
- Say 'types vanish at run time'.
- Contrast parse and safeParse.
- Mention the coerce.boolean trap.