Sub topic 5
Validating Data with parse and safeParse
What this chapter assumes
You should know basic TypeScript types, JavaScript objects and JSON, ES module imports, and try/catch. You should also have a schema like the User object from earlier chapters. This chapter covers the two methods that run a schema against a value: parse and safeParse. It also covers how to choose between them and the mistakes that come up most often.
Every example uses this schema:
import { z } from "zod";
const User = z.object({
id: z.number().int().positive(),
name: z.string().min(1),
nickname: z.string().optional(),
});
type User = z.infer<typeof User>;What parsing does
A schema is only a description until you run it. Parsing takes a value of unknown shape and does one of two things:
- It returns a value that matches the schema, typed as the schema's output type.
- It reports every rule the value broke.
Both methods accept unknown input, so you can pass them anything. That is the point: the schema's input type is not restricted, because the data has not been checked yet.
parse: return the data or throw
parse returns the validated data. If validation fails, it throws a ZodError.
const user = User.parse({ id: 1, name: "Ada" });
// user has type { id: number; name: string; nickname?: string | undefined }
console.log(user.name); // "Ada"
try {
User.parse({ id: -5, name: "" });
} catch (err) {
if (err instanceof z.ZodError) {
console.error(`Rejected with ${err.issues.length} issues`);
} else {
throw err;
}
}The second call fails on two fields, id and name. Zod collects all failures in one pass instead of stopping at the first. The thrown error holds them all in err.issues, so the try block above reports two issues.
parse suits code where invalid data is a programming or deployment error and the program cannot continue. Examples are reading configuration at startup or loading a fixture in a test. In those cases a thrown exception with a clear message is the right outcome.
safeParse: return a result object
safeParse never throws for validation failures. It returns a result object with a success field:
const text = '{"id": 1, "name": ""}';
const result = User.safeParse(JSON.parse(text));
if (result.success) {
console.log(result.data.name);
} else {
for (const issue of result.error.issues) {
console.error(issue.path.join("."), issue.message);
}
}The result is a discriminated union on success:
| Field | When `success` is `true` | When `success` is `false` |
|---|---|---|
| `success` | `true` | `false` |
| `data` | The validated value | Not present |
| `error` | Not present | A `ZodError` |
TypeScript narrows the type when you test result.success. Inside the if branch you can read result.data. Inside the else branch you can read result.error. Reading result.data before the check is a compile error, which stops you from using unvalidated data by accident.
safeParse suits code where bad input is expected and handled as normal control flow. Examples are an HTTP handler that answers 400, a form that shows field messages, or a batch job that skips bad rows.
Choosing between them
The two methods differ only in error handling. Use this guide:
| Situation | Prefer | Reason |
|---|---|---|
| Startup configuration | `parse` | Failing fast with an exception is the goal |
| Request body from a client | `safeParse` | Invalid input is routine and needs a `4xx` response |
| Form submission | `safeParse` | You need the issues to show per-field messages |
| Trusted internal data, such as a test fixture | `parse` | A failure means a bug |
| A pipeline of many records | `safeParse` | One bad record should not stop the rest |
A practical rule is that if you would wrap parse in a try/catch just to turn the error into a value, call safeParse instead. The result object is easier to pass around than an exception.
Wrapping safeParse in your own helper
Many code bases turn a safeParse result into a result type of their own. This keeps Zod details out of the calling code:
type Parsed<T> =
| { ok: true; value: T }
| { ok: false; messages: string[] };
function validate<T>(schema: z.ZodType<T>, input: unknown): Parsed<T> {
const result = schema.safeParse(input);
if (result.success) {
return { ok: true, value: result.data };
}
return {
ok: false,
messages: result.error.issues.map(
(issue) => `${issue.path.join(".") || "(root)"}: ${issue.message}`,
),
};
}
const outcome = validate(User, { id: "7", name: "Grace" });
console.log(outcome);
// { ok: false, messages: [ 'id: ...' ] }The "(root)" fallback covers the case where the whole value has the wrong type. For example, passing null produces an issue whose path is an empty array. The exact message text depends on your Zod version, so do not match on it in code. Match on issue.code or issue.path instead.
Parsing JSON text
JSON.parse returns any in TypeScript's standard library, which silently turns off type checking. Treat its result as unknown and hand it straight to a schema. Remember that JSON.parse itself can throw on malformed text, and that is a different failure from a validation error:
function parseUser(text: string): User | null {
let raw: unknown;
try {
raw = JSON.parse(text);
} catch {
return null; // not valid JSON at all
}
const result = User.safeParse(raw);
return result.success ? result.data : null;
}
console.log(parseUser('{"id": 2, "name": "Linus"}')); // { id: 2, name: 'Linus' }
console.log(parseUser("{not json")); // null
console.log(parseUser('{"id": 2}')); // nullKeeping the two steps separate matters. A try/catch around both would hide which one failed.
What parse returns
The returned value is not always the object you passed in. Three behaviors are worth knowing:
- Unknown keys are removed. By default
z.objectstrips keys the schema does not list. Input{ id: 1, name: "Ada", admin: true }returns{ id: 1, name: "Ada" }. - The result is a new object. Zod builds a fresh value, so changing the original input afterward does not change the parsed data.
- Transforms and defaults are applied. If the schema uses
defaultortransform, the output can differ from the input in value and in type. Later chapters cover these.
const input = { id: 1, name: "Ada", admin: true };
const parsed = User.parse(input);
console.log(parsed); // { id: 1, name: 'Ada' }
console.log(parsed === input); // falseAsynchronous validation
Some rules need to wait, for example checking a database for a taken username. A schema that contains an async refine or transform must be run with the async variants, parseAsync and safeParseAsync. They behave like their sync counterparts but return a promise.
const Username = z
.string()
.min(3)
.refine(async (name) => name !== "admin", { message: "Name is reserved" });
async function main() {
const result = await Username.safeParseAsync("admin");
if (!result.success) {
console.error(result.error.issues[0].message); // "Name is reserved"
}
}
main();If you call the sync parse on a schema with an async rule, Zod throws an error telling you to use the async method. A schema with no async parts also works with the async methods, so you can use them everywhere if that is simpler.
Common mistakes
- Catching too much. A
try/catcharoundparsethat handles every error will also swallow bugs unrelated to validation. Checkerr instanceof z.ZodErrorand rethrow everything else. - Reading
result.datawithout checkingsuccess. TypeScript will not allow it, and casting around the error defeats the purpose. - Passing a type assertion instead of parsing. Writing
body as Usertells the compiler to trust the data. It performs no check. - Expecting
parseto mutate its input. It never does. Use the return value. - Ignoring stripped keys. If a downstream system needs extra fields, the schema must declare them or use a schema mode that keeps unknown keys.
- Matching error messages in code. Messages can change between versions. Use
issue.codeandissue.path.
Exercise
A handler receives the string '{"id": 3, "name": "Ada", "role": "admin"}' and runs const user = User.parse(JSON.parse(text)); using the User schema from this chapter. What does user contain, and which parts of the call could throw?
Show answer
user is { id: 3, name: "Ada" }. The role key is not in the schema, so Zod strips it. Two parts can throw: JSON.parse throws a SyntaxError if the text is not valid JSON, and User.parse throws a ZodError if the parsed value fails validation. This input is valid JSON and passes the schema, so neither throws here.
Exercise
Rewrite const user = User.parse(data); so that invalid input produces an HTTP-style status of 400 and a list of messages instead of an exception. Which method do you use, and what do you read from the failure result?
Show answer
Use safeParse. Check result.success. If it is false, respond with status 400 and build the messages from result.error.issues, for example result.error.issues.map((i) => ${i.path.join(".")}: ${i.message}). If it is true, continue with result.data.