In Zod 4, after safeParse succeeds on a webhook body, why pass result.data inward instead of the original body object?
answer
- a new value, not the input
- extra keys left behind
- defaults and transforms land in the output
- parse once at the edge
basics
~20 sZod'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.
solid answer
~40 sIn Zod 4 a successful parse returns a value Zod built while walking the schema, not the object you passed in. A plain `z.object()` strips keys its shape does not declare, `.default()` fills missing fields and `.transform()` replaces raw values, so the original body can still carry an extra key like `isAdmin`, lack a defaulted field or hold an untransformed string. Only `result.data` has the schema's output type. The pattern is parse once at the edge, then pass `result.data` inward to functions typed with `z.infer<typeof Schema>`, so the compiler rejects raw input anywhere past the boundary. A boolean `.validate()` does not help here: it returns no value and narrows only to the schema's input type.
code
typescript · 15 linesimport * as z from "zod";
const RefundEvent = z.object({
id: z.string(),
currency: z.string().transform((c) => c.toUpperCase()),
partial: z.boolean().default(false),
});
const body: unknown = { id: "evt_9", currency: "eur", isAdmin: true };
const result = RefundEvent.safeParse(body);
if (result.success) {
console.log(result.data); // { id: 'evt_9', currency: 'EUR', partial: false }
console.log(body); // { id: 'evt_9', currency: 'eur', isAdmin: true }
}go deeper
Remember that a successful parse hands back a new value and that this value, not the input, is the one you pass on.
Explain the three ways the output differs from the input: unknown keys stripped by z.object(), defaults filled, transforms applied, and why only the output matches the inferred type.
Show how forwarding the original body reopens mass assignment and type lies, and how typing internal functions with the parsed type makes the compiler enforce parse-once.
Treat parse-once as an architectural rule: one boundary per input source, raw values typed unknown only there, and casts of raw input to schema types banned in review.
## What a successful parse gives back When `schema.parse(input)` or `schema.safeParse(input)` succeeds in Zod 4, the value you get back (`parse`'s return value, or `result.data`) is **not the object you passed in**. Zod builds its output as it walks the schema. The basic-usage docs describe the result as a strongly typed deep clone of the input, and the object schema really does allocate a new object for its output. Along the way, three things can make the output differ from the input: - **Unknown keys are dropped.** A plain `z.object()` strips keys its shape does not declare. They are not an error by default; they are simply left out of the output. - **Defaults are filled.** A field declared with `.default(...)` that is missing from the input appears in the output with its default value. - **Transforms are applied.** A field with `.transform(...)` holds the transformed value in the output, possibly of a different type than the input. How defaults and transforms are declared, and how unknown-key handling can be switched to rejecting or keeping extra keys, belong to the lessons on refinements and transforms and on object composition. What matters here is the consequence: **only the returned value matches the type Zod inferred for the schema.** ## What the original still holds Picture a webhook receiver for a payment provider. The handler calls `safeParse(body)`, checks `success`, and then passes `body` to the next function because "it has been validated". The original body is still whatever the sender put on the wire: | | Original `body` | `result.data` | |---|---|---| | Unknown keys such as `isAdmin` | still present | stripped by `z.object()` | | Missing field with a default | still missing | filled with the default | | Field with a transform | raw input value | transformed value | | Static type | `unknown` (or a cast) | the schema's output type | So code downstream that spreads `body` into a database write can still carry a key the schema never allowed, and code that expects the default or the transformed value gets the raw one. Worse, the compiler cannot warn you: if you cast `body` to the inferred type, the cast is a claim nobody checked. ## Parse once, then trust The working pattern is to **parse at the edge and pass the parsed value inward**: 1. Receive the raw input as `unknown` at the boundary (the request handler, the webhook receiver, the client wrapper for a third-party API). 2. Call `safeParse` once and handle failure right there. 3. Pass `result.data` to the rest of the code, whose functions accept the inferred output type (`z.infer<typeof Schema>`), never `unknown`. 4. Do not parse again further in. A second parse of the same value repeats the work, re-runs any refinements, and suggests nobody knows where the boundary is. It can even fail outright: if a transform turned a date string into a `Date`, the parsed value no longer matches what the schema expects as input. Because internal functions demand the parsed type, the compiler now marks any path that tries to hand them raw input. The schema becomes the single place where the shape is checked. ## A boolean check is not a parse Zod 4 also offers `schema.validate(input)` (and `validateAsync`), which only answers whether the input is acceptable. It returns a boolean, never builds an error, and acts as a TypeScript **type guard on the schema's input type**. That makes it useful for a quick yes-or-no, but it is not a substitute for parsing at a boundary: - it gives you **no new value**, so unknown keys are not stripped, defaults are not filled and transforms are not applied; - it narrows to the **input** type, not the output type, so with a transform or default in the schema the narrowed variable is still not what the rest of the code expects. ## Mistakes interviewers listen for - Treating `safeParse` as an in-place check and forwarding the original object. - Assuming `z.object()` rejects unknown keys. By default it strips them. - Casting the original input to `z.infer<typeof Schema>` after a successful parse instead of using the parsed value. - Re-parsing the same value in every layer "for safety" instead of typing internal functions with the parsed type. - Using `.validate()` at a boundary that needs stripped keys, defaults or transformed values.
- In Zod 4, how would you make the type system stop a raw body from reaching your business logic?Type every internal function with the schema's output type, `z.infer<typeof Schema>`, and keep `unknown` only at the boundary. A raw body typed `unknown` then cannot be passed in without a cast, so the only clean path is through `safeParse` and `result.data`. Casting the raw body to the inferred type defeats this, so treat such casts as review findings.
- In Zod 4, when is the boolean schema.validate(input) the right call instead of safeParse?When you only need a yes or no and will not use the value, for example filtering items or a guard before choosing a code path. It builds no error and returns no value, so it is cheaper on invalid input. At a boundary that needs stripped keys, filled defaults or transformed values, or that must report what failed, use `safeParse`.
- safeParse checks the body in place, so body and result.data are the same object
- z.object() rejects unknown keys by default
- Casting the original body to the inferred type after a successful parse is equivalent
- Re-parsing the same value in every layer makes the code safer
- validate() returns the same value safeParse would, just faster
Assumes Zod 4.6.5; .validate() is a Zod 4 addition with no Zod 3 equivalent, while parse returning a new value with unknown keys stripped is unchanged from Zod 3.