Nested and Recursive Schemas
You'll learn how to validate deeply nested objects and self-referential structures like trees using Zod.
Understanding Nested Structures
Many real-world data structures contain objects within objects, or even reference themselves. Think of a file system: a folder contains files and other folders. Or a comment thread where each comment can have replies that are themselves comments. Validating these structures requires schemas that can express arbitrary depth.
Deeply Nested Objects
For nested objects, you simply compose schemas together:
import { z } from 'zod';
const AddressSchema = z.object({
street: z.string(),
city: z.string(),
zipCode: z.string()
});
const UserSchema = z.object({
name: z.string(),
address: AddressSchema,
billingAddress: AddressSchema.optional()
});
const user = UserSchema.parse({
name: "Alice",
address: { street: "123 Main", city: "NYC", zipCode: "10001" }
});
Each schema validates its own level independently, creating a validation chain.
Recursive Schemas
For self-referential structures, use z.lazy() to defer schema definition until runtime:
const CategorySchema = z.object({
name: z.string(),
subcategories: z.lazy(() => z.array(CategorySchema))
});
const tree = CategorySchema.parse({
name: "Electronics",
subcategories: [
{ name: "Phones", subcategories: [] },
{ name: "Laptops", subcategories: [
{ name: "Gaming", subcategories: [] }
]}
]
});
The z.lazy() wrapper prevents infinite loops during schema construction by deferring the reference until validation runs.
Key Takeaway: Nest schemas directly for hierarchical objects, and use z.lazy() for self-referential structures where the schema needs to reference itself recursively.