Sub topic 3
Describing objects with z.object
This chapter assumes you know basic TypeScript types, JavaScript objects and JSON, and ES module imports. It also assumes you have seen a few primitive Zod schemas such as z.string() and z.number(). Here you will describe whole objects, including nested ones, and learn how Zod treats keys that your schema does not mention.
What z.object does
Most data you validate is an object: a JSON body, a row from a database, a parsed config file. z.object takes a plain JavaScript object called the shape. Each key of the shape is a key you expect in the data, and each value is the schema for that key's value.
import { z } from "zod";
const User = z.object({
id: z.number().int().positive(),
name: z.string().min(1),
active: z.boolean(),
});
const ok = User.safeParse({ id: 7, name: "Ada", active: true });
console.log(ok.success); // true
const bad = User.safeParse({ id: "7", name: "Ada" });
console.log(bad.success); // falseThe second call fails for two reasons. id is a string instead of a number, and active is missing. Zod does not stop at the first problem in an object. It checks every key and collects all failures, so one error report can describe the whole bad payload. The chapter on error handling covers how to read those reports. For now, a plain success flag is enough.
Every key is required by default
A key in the shape is required unless you say otherwise. Required means the value must be present and must pass its schema. A missing key is treated as undefined, and z.string() rejects undefined.
This has a practical consequence. You do not need a separate "required" setting for most fields. You describe what a valid value looks like, and anything else fails, including undefined and null.
To allow a key to be absent, wrap its schema in .optional():
import { z } from "zod";
const Profile = z.object({
name: z.string(),
bio: z.string().optional(),
});
console.log(Profile.safeParse({ name: "Ada" }).success); // true
console.log(Profile.safeParse({ name: "Ada", bio: undefined }).success); // true
console.log(Profile.safeParse({ name: "Ada", bio: null }).success); // falseThe last line fails because null is a different value from undefined. If null should be accepted, you need .nullable(). Optional, nullable, and default values get their own chapter, so treat .optional() here only as a preview.
What happens to keys you did not declare
JSON from outside your program often contains keys you never listed. By default, Zod removes them from the result. This default is called strip mode. The output object contains only the keys in your shape.
import { z } from "zod";
const Point = z.object({ x: z.number(), y: z.number() });
const result = Point.parse({ x: 1, y: 2, z: 3, label: "origin" });
console.log(result); // { x: 1, y: 2 }Stripping is a safe default for one important reason. If you validate a request body and then save the result, unexpected fields such as isAdmin: true never reach your database layer. But stripping also hides mistakes. If a client misspells nickname as nikname, the request passes and the field silently disappears.
Zod gives you three other behaviors for unknown keys.
| Mode | Method | Unknown keys |
|---|---|---|
| Strip (default) | `z.object({...})` | Removed from the output, no error |
| Strict | `.strict()` | Cause a validation error |
| Passthrough | `.passthrough()` | Kept in the output, unchecked |
| Catchall | `.catchall(schema)` | Kept, and each value must match `schema` |
The following code shows all four behaviors on the same input.
import { z } from "zod";
const shape = { x: z.number() };
const input = { x: 1, extra: "hello" };
console.log(z.object(shape).parse(input)); // { x: 1 }
console.log(z.object(shape).passthrough().parse(input)); // { x: 1, extra: "hello" }
console.log(z.object(shape).catchall(z.string()).parse(input)); // { x: 1, extra: "hello" }
console.log(z.object(shape).strict().safeParse(input).success); // falseUse these modes to match how much you trust the source. Use strict for config files, where a misspelled key is a bug you want to hear about. Use strip for public request bodies, where you want clean output without rejecting clients that send extras. Use passthrough only when you forward the data to something else and must not lose fields.
Nesting objects
A schema value can itself be an object schema. Nest as deep as the data goes.
import { z } from "zod";
const Order = z.object({
id: z.string(),
customer: z.object({
name: z.string().min(1),
address: z.object({
city: z.string(),
postcode: z.string().length(5),
}),
}),
});
const result = Order.safeParse({
id: "o-1",
customer: { name: "Ada", address: { city: "Leeds", postcode: "123" } },
});
if (!result.success) {
for (const issue of result.error.issues) {
console.log(issue.path.join("."), "->", issue.message);
}
}
// customer.address.postcode -> (a message about the required length)Each issue has a path, an array that names the route from the root to the failing value. Here it is ["customer", "address", "postcode"]. The path is what lets you point at the exact field in a nested payload.
When a nested object grows large or appears in several places, give it its own name and reuse it:
import { z } from "zod";
const Address = z.object({
city: z.string(),
postcode: z.string().length(5),
});
const Customer = z.object({
name: z.string().min(1),
address: Address,
});
const Shipment = z.object({
from: Address,
to: Address,
});Named pieces are easier to test and read. The later chapter on composition shows how to derive new object schemas from existing ones.
Inspecting a schema with shape
An object schema keeps its shape available as .shape. You can use this to pull out a single field schema and validate a value on its own, for example one form field as the user types.
import { z } from "zod";
const User = z.object({
id: z.number().int().positive(),
name: z.string().min(1),
});
const nameSchema = User.shape.name;
console.log(nameSchema.safeParse("").success); // false
console.log(nameSchema.safeParse("Ada").success); // trueCommon mistakes
These are the errors intermediate users hit most often with z.object.
- Expecting extra keys to fail. The default strips them. If you want an error, add
.strict(). - Confusing missing,
undefined, andnull..optional()accepts missing andundefined. It does not acceptnull. - Forgetting that parse returns a new object. With strip mode, the result is not the same object you passed in. Always use the returned value, not the original input, after validation.
- Validating the wrong thing.
z.objectexpects an actual object. If you pass a JSON string, it fails with a type error. RunJSON.parsefirst, then validate the result. - Passing arrays or
nulland expecting a helpful error. Arrays andnullare not accepted as objects. Zod reports them as the wrong type at the root, with an empty path.
Practice
Exercise
A client sends the body {"name": "Ada", "email": "[email protected]", "role": "admin"} to an endpoint validated with z.object({ name: z.string(), email: z.string() }). What does parse return, and which change would make the request fail instead?
Show answer
parse returns { name: "Ada", email: "[email protected]" }. The unknown key role is stripped without an error, which also stops a client from smuggling in a privilege field. Adding .strict() to the schema makes the same body fail validation because of the unrecognized role key.
Exercise
Write a schema for { "title": "Report", "meta": { "pages": 12 } } where pages must be a positive integer. What is the path of the issue when pages is -3?
Show answer
Use z.object({ title: z.string(), meta: z.object({ pages: z.number().int().positive() }) }). The issue path is ["meta", "pages"], which issue.path.join(".") renders as meta.pages.