safeParse
Zod · Reference cheat sheet
safeParse
Zod · Reference cheat sheet
📋 Overview
safeParse returns a discriminated result instead of throwing. Prefer it at HTTP/form boundaries where invalid input is expected.
🔧 Core concepts
| API | Behavior |
|---|---|
schema.parse(data) | Returns value or throws ZodError |
schema.safeParse(data) | \{ success, data \} or \{ success, error \} |
schema.parseAsync / safeParseAsync | Async refinements/transforms |
error.flatten() | Field errors for forms |
error.format() | Nested error tree |
💡 Examples
Branch on success:
const result = User.safeParse(payload);
if (!result.success) {
console.error(result.error.flatten());
return;
}
console.log(result.data.email);HTTP handler style:
const parsed = Body.safeParse(await req.json());
if (!parsed.success) {
return Response.json(parsed.error.flatten(), { status: 400 });
}flatten for UI:
const { fieldErrors, formErrors } = error.flatten();⚠️ Pitfalls
- After
success === true, TypeScript narrowsdata— don't accessdataon the failure branch. - Swallowing
errorwithout logging loses diagnostics. parsein a hot request path without try/catch can crash the process if unhandled.