🔧 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.

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
});