πŸ”§ Error Fixes
Β· 1 min read

Zod: ZodError β€” Validation Failed β€” How to Fix It


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: TypeScript: Type X Is Not Assignable to Type Y Β· What is TypeScript

πŸ“˜