skip to content

In Zod 4, what does z.object do with keys the schema does not declare, and when would you use z.strictObject or z.looseObject instead?

level: middleimportance: must knowfreq 70%

answer

  1. silent by default
  2. returned value, not the raw body
  3. unrecognized_keys issue
  4. catchall decides the mode
  5. mode does not cascade into nested objects

basics

~20 s

Zod 4's z.object strips undeclared keys from the parsed result without raising an issue. z.strictObject fails the parse with an unrecognized_keys issue, and z.looseObject copies unknown keys through unvalidated. Each mode applies only to the object schema it is set on.

solid answer

~50 s

Plain `z.object` is in strip mode: the parse succeeds and the returned object holds only the declared keys, so `{ name: "Ada", role: "admin" }` against a schema without `role` comes back as `{ name: "Ada" }`. That blocks mass assignment, but only if the handler uses the value `parse` returned rather than the original body. `z.strictObject` fails instead, with one `unrecognized_keys` issue listing the extra keys, which suits endpoints where a misspelt field such as `emial` should be a client error rather than silently dropped. `z.looseObject` keeps unknown keys in the output without validating them, for payloads you forward but only partly own, and `.catchall(schema)` validates every unknown key against one schema. The mode belongs to one object: a nested `z.object` inside a strict object still strips. Zod 3 spelled these `.strict()` and `.passthrough()`, which Zod 4 keeps as legacy methods.

code

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

const body = { name: "Ada", emial: "[email protected]", role: "admin" };

const Strip = z.object({ name: z.string(), email: z.email().optional() });
console.log(Strip.parse(body)); // { name: "Ada" }

const Strict = z.strictObject({ name: z.string(), email: z.email().optional() });
const result = Strict.safeParse(body);
if (!result.success) {
  const issue = result.error.issues[0];
  console.log(issue.code, issue.message);
  // unrecognized_keys Unrecognized keys: "emial", "role"
}

const Loose = z.looseObject({ name: z.string() });
console.log(Loose.parse(body));
// { name: "Ada", emial: "[email protected]", role: "admin" }

go deeper

for a junior

Remember the default: z.object drops keys it does not declare and still succeeds. Know the two other builders by name, z.strictObject and z.looseObject.

for a middle

Explain what each mode returns, the unrecognized_keys issue strict mode raises, and why the protection only exists in the value parse returned.

for a senior

Show you know the mode is per object and does not cascade, that derived schemas inherit it, and that strip silently hides client typos you will never see in logs.

for a principal

Frame strip versus strict as a trade between silent data loss and brittleness under client version skew, and note Zod offers no global switch to enforce either.

## The three unknown-key modes An **unknown key** is a property on the input that the object schema's shape does not declare. Every Zod 4 object schema has exactly one policy for such keys, and the function that builds the schema picks it: | Builder | Unknown keys on the input | Parse result | |---|---|---| | `z.object({...})` | allowed, not validated | **stripped** from the output | | `z.strictObject({...})` | rejected | the parse fails with an `unrecognized_keys` issue | | `z.looseObject({...})` | allowed, not validated | **copied through** to the output | | `z.object({...}).catchall(s)` | validated against `s` | kept when they pass `s`, an issue when they fail | Internally the modes differ only in the object's **catchall**, the schema applied to undeclared keys: a strict object uses `z.never()`, a loose object uses `z.unknown()`, and a plain object has none, which means strip. That is why `.catchall()` overrides whichever mode the schema had before. ## Strip is the default, and what it buys you A plain `z.object` succeeds on extra keys and returns a **new object** containing only the declared ones. Three consequences follow: - **Mass assignment protection.** A client that posts `role: "admin"` to a profile endpoint whose schema does not declare `role` gets that key dropped before it reaches your persistence code. - **The protection lives in the returned value only.** `parse` does not mutate its input. A handler that validates the body and then spreads the original request body into an insert has thrown the protection away. - **Strip is silent.** No issue is raised, nothing is logged, and nothing reports which keys were removed. A client that misspells `email` as `emial` receives a success, and the email never changes. ## When strict pays off `z.strictObject` turns every undeclared key into a failed parse. The single issue has code `unrecognized_keys`, a `keys` array naming every offender, and a default English message such as `Unrecognized keys: "emial", "role"`. Reach for it when: 1. A misspelt or stale field name should come back to the client as an error rather than vanish. 2. Any unexpected field on a write endpoint signals a client bug or someone probing for a writable column. 3. Object options inside a union must not overlap: with strip, an input carrying extra keys can satisfy the narrower option, so a strict narrower option makes the branches mutually exclusive. The cost is brittleness. A newer client that sends a field the server does not know yet, or a third-party payload that gains a field, now fails outright. ## When loose is the right call `z.looseObject` validates the declared keys and keeps everything else as it arrived. It fits a gateway that forwards a payload it only partly understands, or an object that carries an open-ended bag of extra attributes. Two things to remember: - The extra keys are **not validated** at all. Their values are whatever the sender put there. - The inferred output type gains a `Record<string, unknown>` part, so downstream code sees the extras as `unknown` and must check them before use. When the extras should all share one shape, for example string labels, `.catchall(z.string())` is stricter than loose: unknown keys are kept, but each value must pass the catchall schema. ## The mode belongs to one object schema - **It does not cascade.** A `z.object` nested inside a `z.strictObject` still strips its own unknown keys. Strictness has to be declared on each object that needs it. - **Derived schemas keep it.** `.extend()`, `.pick()`, `.omit()` and `.partial()` called on a strict schema return a strict schema. - **Changing it means rebuilding from the shape:** `z.strictObject(Base.shape)` or `z.object(Strict.shape)`, or spread `...Base.shape` into the builder you want. - **There is no global switch.** `z.config()` carries locale and JIT settings, not an unknown-key default, so a team-wide choice has to live in convention or a shared helper. ## What changed from Zod 3 Zod 3 expressed the modes as methods: `.strict()`, `.passthrough()` and `.strip()`. Zod 4's changelog moves to the top-level `z.strictObject()` and `z.looseObject()` and calls the old methods legacy: they still work and will not be removed. In the source, `.passthrough()` carries a deprecation note pointing to `z.looseObject()` or `.loose()`, `.strict()` carries a softer "consider `z.strictObject(A.shape)`" note, and `.strip()` is documented as an unnecessary call because strip is the default. The default itself did not change between the two versions.

  • In Zod 4, a z.strictObject has an address field built with z.object. Is an unknown key inside address rejected?
    No. The mode belongs to each object schema, and the nested `z.object` keeps its own strip mode, so the unknown key inside `address` is silently removed. To reject it, build `address` with `z.strictObject` as well. Strictness never cascades down the tree.
  • In Zod 4, how does .catchall() differ from z.looseObject?
    `z.looseObject` keeps unknown keys without validating them, which is the same as a catchall of `z.unknown()`. `.catchall(schema)` also keeps them but runs each value through `schema`, so `.catchall(z.string())` accepts an extra `label: "blue"` and fails on `label: 42`. It overrides any strict or loose mode the object had.
  • You already have a plain z.object schema and need a strict version of it in Zod 4. How do you get one?
    Rebuild it from its shape: `z.strictObject(Base.shape)`, or spread `...Base.shape` into `z.strictObject` alongside extra fields. The legacy `.strict()` method still works, but Zod 4 recommends the top-level builders because the mode is then visible where the schema is declared.

A clerk copying a paper form into a database. In strip mode the clerk copies only the printed boxes and bins whatever was scribbled in the margins; in strict mode the clerk hands the form back if anything is written in the margins; in loose mode the margin notes are stapled to the record unread. A form clipped inside the main form gets its own clerk with its own habit.

  • Says z.object rejects unknown keys by default in Zod 4.
  • Believes stripping protects the handler even when it keeps using the raw request body.
  • Thinks z.strictObject makes every nested object strict as well.
  • Assumes z.looseObject validates the extra keys it passes through.
  • Claims Zod 4 removed .strict() and .passthrough(), so Zod 3 code stops compiling.

Assumes Zod 4; z.strictObject and z.looseObject replace Zod 3's .strict() and .passthrough(), which Zod 4 keeps as legacy methods. Strip is the default in both versions.