ZodError: [ { code: 'invalid_type', expected: 'string', received: 'undefined' } ]
Zod validation failed because the data doesnβt match the schema.
Why this happens
Zod validates data at runtime against a schema you define. When the input shape doesnβt match β a required field is missing, a value has the wrong type, or a string fails a regex check β Zod throws a ZodError with details about every failing field. This commonly happens with API responses, form data, or environment variables that donβt match expectations.
Fix 1: Use safeParse instead of parse
const schema = z.object({ name: z.string(), age: z.number() });
// β Throws on invalid data
const data = schema.parse(input);
// β
Returns result object
const result = schema.safeParse(input);
if (!result.success) {
console.log(result.error.flatten());
} else {
console.log(result.data);
}
Fix 2: Make fields optional or add defaults
const schema = z.object({
name: z.string(),
age: z.number().optional(),
role: z.string().default('user'),
});
Fix 3: Transform input
const schema = z.object({
age: z.string().transform(Number), // Accept string, convert to number
});
Alternative solutions
Use .passthrough() to allow extra fields, or .strip() to silently remove them:
const schema = z.object({ name: z.string() }).passthrough();
schema.parse({ name: 'Jo', extra: true }); // β
No error
Prevention
- Log
result.error.flatten()during development to see exactly which fields fail and why. - Validate environment variables at app startup with Zod so missing config fails fast instead of at runtime.
Related resources
Related: TypeScript: Type X Is Not Assignable to Type Y Β· What is TypeScript