Execution & Safe Parsing
Learn when to use parse(), safeParse(), parseAsync(), and safeParseAsync().
Execution Method Matrix
• .parse(data): Synchronous; returns output or throws ValidationError. • .safeParse(data): Synchronous; returns { success: true, data } or { success: false, error, issues }. • .parseAsync(data): Asynchronous; returns Promise<output> or rejects. • .safeParseAsync(data) / .spa(data): Asynchronous; returns Promise<ParseResult>.
Safe Parsing Pattern
Safe parsing avoids try/catch boilerplate and provides TypeScript type narrowing:
Schema Definition
const result = UserSchema.safeParse(req.body);
if (!result.success) {
// result.error is ValidationError
return res.status(400).json({ errors: result.error.flatten() });
}
// result.data is strongly typed
console.log(result.data.id);The Synchronous Safety Rule
Calling synchronous .parse() or .safeParse() on a schema containing asynchronous transforms or refinements will throw an explicit error instructing you to use .parseAsync() or .safeParseAsync().
