skip to content

Parsing at the Boundary

parse throws a ZodError on bad input and safeParse returns a success-or-error result instead. Interviewers ask which belongs at an API boundary and what a parsed value lets the rest of the code skip.

on this pageshow

explore

questions

4

In Zod 4, what happens when schema.parse() and schema.safeParse() receive invalid input, and how do you read each result?

level: juniorimportance: must knowfreq 80%

answer

  1. one throws, one returns
  2. try/catch versus a plain if
  3. a flag that narrows the result
  4. data on one branch, error on the other

basics

~20 s

Zod's parse() returns the typed value or throws a ZodError when input fails the schema. safeParse() does not throw on invalid input; it returns { success: true, data } or { success: false, error } holding a ZodError.

solid answer

~40 s

`schema.parse(input)` returns the parsed value, typed as the schema's output, or throws a `ZodError` whose `issues` array lists every problem, each with a `code`, a `path` and a `message`. `schema.safeParse(input)` runs the same validation but returns a result object instead: `{ success: true, data }` or `{ success: false, error }`. That result is a discriminated union on `success`, so after `if (!result.success)` TypeScript treats `result.error` as a `ZodError`, and in the other branch `result.data` as the parsed type. I use `parse` when a failure should abort the operation and something upstream already catches errors, and `safeParse` when bad input is an expected outcome I handle on the spot, such as an incoming request.

code

typescript · 27 lines
typescript
import * as z from "zod";

const PaymentEvent = z.object({
  id: z.string(),
  type: z.string(),
  amount: z.number(),
});

const raw: unknown = JSON.parse('{"id":"evt_1","type":"payment.succeeded","amount":"1200"}');

// parse: returns the value or throws
try {
  const event = PaymentEvent.parse(raw);
  console.log(event.amount);
} catch (err) {
  if (err instanceof z.ZodError) {
    console.log(err.issues[0].path); // [ 'amount' ]
  }
}

// safeParse: returns a result you branch on
const result = PaymentEvent.safeParse(raw);
if (!result.success) {
  console.log(result.error.issues[0].code); // 'invalid_type'
} else {
  console.log(result.data.amount); // typed as number
}

go deeper

for a junior

Recall the two shapes cleanly: parse gives a value or throws a ZodError, safeParse gives success with data or failure with error. Write the if on success from memory.

for a middle

Explain that both calls run the same validation and differ only in how failure is reported, and show how the success flag narrows data and error for the compiler.

for a senior

Show you pick by failure semantics: safeParse where bad input is expected and answered locally, parse where failure should abort and an upstream handler already distinguishes a ZodError from a real bug.

for a principal

Frame the choice as team convention: one rule per kind of boundary for which call to use, so reviewers can spot a thrown validation error leaking out as a server failure.

## Two calls, one validation run A **Zod schema** describes the shape a value must have. You hand it an input typed `unknown` (a parsed JSON body, a webhook payload, a value read from storage) and ask it to check that input. Zod gives you two everyday calls for that, and they run exactly the same validation. The only difference is **how they report failure**: - `schema.parse(input)` returns the parsed value when the input is valid and **throws** a `ZodError` when it is not. - `schema.safeParse(input)` never throws for invalid input. It **returns a result object** that says whether parsing worked and carries either the value or the error. Both collect problems across the whole input instead of stopping at the first bad field, so a payload with two wrong fields produces two issues. ## parse: return the value or throw `parse` suits code where a failure should abort the current operation and something higher up already handles thrown errors. On success, its return type is the schema's output type, so the value is fully typed from that line on. On failure, you catch the error and check what it is: ```ts try { const event = PaymentEvent.parse(raw); // event is typed from here on } catch (err) { if (err instanceof z.ZodError) { console.log(err.issues); } } ``` The thrown `ZodError` has an `issues` array. Each **issue** has a `code` (for example `invalid_type`), a `path` (the keys that lead to the bad value, such as `['amount']`) and a human-readable `message`. By default an issue does not include the offending input value; Zod adds it only when you pass `reportInput: true` in the parse options. Turning issues into field messages for a client is covered with Zod's error formatting. ## safeParse: a result you branch on `safeParse` suits code where invalid input is an **expected outcome**, not an exception: an incoming request, a webhook from a third party, a form submission. It returns one of two shapes: | Outcome | Shape | What you can read | |---|---|---| | Valid input | `{ success: true, data }` | `data`, typed as the schema's output | | Invalid input | `{ success: false, error }` | `error`, a `ZodError` with the same `issues` as `parse` would throw | There is no `try`/`catch`. You write an `if` on the `success` flag and handle both outcomes right where you parsed. ## Narrowing on the success flag The result type is a **discriminated union**: a union of object types that share a literal-typed property (`success: true` or `success: false`) the compiler can use to tell them apart. Checking that flag narrows the result: 1. After `if (!result.success)`, TypeScript knows `result.error` is a `ZodError`. 2. In the other branch, it knows `result.data` is the parsed type. 3. Before any check, `result.data` may be `undefined`, so reading it without the check gives you a value the compiler will not treat as the parsed type. The general rules of how TypeScript narrows a discriminated union are covered in the TypeScript material; what matters here is that Zod's result is shaped so that one `if` gives you a typed value. ## Which one to reach for - **`safeParse`** for untrusted input that will sometimes be wrong and needs a specific response: a request body, a webhook payload, a response from an API you do not control. - **`parse`** where a failure means the program cannot sensibly continue, such as checking configuration at startup, or inside code whose callers already turn thrown errors into a response. - **Async variants**: if a schema contains async refinements or transforms, use `parseAsync` or `safeParseAsync`. They behave like their synchronous twins but return a Promise. Whichever you choose, use the **value Zod returns**, not the input you passed in, because the returned value is what matches the schema. ## Common mistakes - Expecting `parse` to return `null` or `undefined` on bad input. It throws. - Wrapping `safeParse` in `try`/`catch` to catch validation failures. Invalid input does not throw; it comes back as `success: false`. - Reading `result.data` without first checking `result.success`. On failure there is no `data`. - Believing `safeParse` is a lighter check that skips rules. It runs the same schema as `parse`. - Catching everything after `parse` and treating every error as a validation failure. Check `instanceof z.ZodError` so a real bug is not reported as bad input.

  • In Zod 4, does safeParse ever throw?
    Not for invalid input; that always comes back as `success: false`. It does throw when the schema contains an async refinement or transform, because a synchronous call cannot wait for a Promise; Zod throws a plain `Error` telling you to use `.parseAsync()`. Bugs inside your own refinement code can also escape. So `safeParse` removes the try/catch for validation failures, not for every possible error.
  • In Zod 4, if a payload has three wrong fields, how many issues does the ZodError contain?
    Three, one per wrong field, each with its own `path`. Zod checks every field of an object rather than stopping at the first failure, so a client can be told about all of them in one response. Within a single field, though, once the value fails its base type its further checks are skipped, so a string field that received a number reports the type problem only.

  • parse returns null or undefined when the input is invalid
  • safeParse is a lighter check that skips some of the schema's rules
  • You need try/catch around safeParse to catch validation failures
  • result.data is always set, so checking result.success is optional
  • Zod stops at the first invalid field and reports only that one
open as a page

In Zod 4, after safeParse succeeds on a webhook body, why pass result.data inward instead of the original body object?

level: middleimportance: should knowfreq 50%

basics

~20 s

Zod's result.data is a new value built from the schema: z.object() drops unknown keys by default, defaults are filled and transforms applied. The original body still holds whatever the sender sent, so only result.data matches the inferred type.

open as a page

A Zod 4 webhook schema gains an async refinement that looks up the event ID, and safeParse now throws 'Encountered Promise during synchronous parse'. Why, and what fixes it?

level: seniorimportance: should knowfreq 35%

basics

~20 s

Zod's synchronous parse and safeParse cannot await, so when a refinement returns a Promise they throw a plain Error instead of reporting an issue. Parse that schema, and every schema embedding it, with safeParseAsync or parseAsync.

open as a page

As the lead standardising Zod 4 in a TypeScript service, which parse call would you mandate at each boundary, and what does parse-once-then-trust commit the team to?

level: principalimportance: should knowfreq 30%

basics

~20 s

With Zod, pick the call by who owns a failure: parse for startup config so a bad deploy crashes, safeParse for requests, third-party responses and stored JSON. Pass only parsed values inward, typed with z.infer, and treat schemas as contracts.

open as a page