safeParse

The Zod method that checks data against a schema and returns a success flag with either the parsed data or the errors, instead of throwing.

In more detail

parse throws an exception on invalid data, while safeParse returns { success: true, data } or { success: false, error }. Route handlers prefer safeParse because they can turn the error list into a clean 400 or 422 response instead of an unhandled crash.

Example

const res = EnvSchema.safeParse(process.env); if (!res.success) process.exit(1)

Related terms

Taught in

References