Optional, Nullable, and Default Values
You'll learn how to make your Zod schemas flexible by handling missing, null, or undefined values gracefully.
What This Solves
In real-world applications, not every field is always present. A user profile might have an optional bio, an API response might include null for missing data, or you might want sensible defaults when values are absent. Zod provides three modifiers to handle these cases precisely.
The Three Modifiers
.optional()
Allows a value to be undefined or match the schema. Think of it like marking a form field as "not required"—it's okay if the user leaves it blank.
const userSchema = z.object({
username: z.string(),
bio: z.string().optional() // can be undefined or a string
});
userSchema.parse({ username: "alice" }); // ✓ valid
userSchema.parse({ username: "alice", bio: "Developer" }); // ✓ valid
.nullable()
Allows a value to be null or match the schema. This is useful when APIs explicitly return null to indicate "no value."
const profileSchema = z.object({
avatar: z.string().url().nullable() // can be null or a valid URL
});
profileSchema.parse({ avatar: null }); // ✓ valid
.default()
Provides a fallback value when the field is undefined. Like setting factory defaults on a device—if nothing is specified, use this.
const settingsSchema = z.object({
theme: z.string().default("light")
});
settingsSchema.parse({}); // { theme: "light" }
settingsSchema.parse({ theme: "dark" }); // { theme: "dark" }
You can also chain them: .nullable().default("fallback") creates a schema that accepts null but replaces undefined with a default.
Key Takeaway: Use .optional() for values that may be absent, .nullable() for explicit null values, and .default() to provide fallback values—giving you precise control over how missing data is handled.