Parsing and Safe Parsing
You'll learn the crucial difference between Zod's parse() and safeParse() methods for handling validation results.
Two Ways to Validate
When you use a Zod schema to validate data, you have two choices for how you want to receive the result:
parse() — The strict bouncer. It validates your data and either returns the validated value or throws an error immediately if validation fails. This is great when you want validation failures to crash your program or be caught by a try-catch block.
safeParse() — The diplomatic messenger. It always returns an object describing what happened. No errors are thrown. Instead, you get a result object with a success property you can check. If success is true, the validated data lives in the data property. If success is false, error details are in the error property.
When to Use Each
Use parse() when failure should stop execution—like validating required environment variables at startup:
const port = z.number().parse(process.env.PORT); // throws if invalid
Use safeParse() when you want to handle errors gracefully—like validating user input in a form:
const result = userSchema.safeParse(formData);
if (result.success) {
console.log("Valid user:", result.data);
} else {
console.log("Validation errors:", result.error);
}
Think of parse() as a guard that won't let bad data through, and safeParse() as a reporter that tells you what happened without making a scene.
Key Takeaway: Use parse() when validation failures should throw errors (fail-fast), and safeParse() when you need to handle validation results as data (error handling).