skip to content

In Zod 4, what does z.coerce.number() do to query-string values such as "42", "" and "abc", and what does it accept silently?

level: middleimportance: must knowfreq 58%

answer

  1. built-in constructor, then the check
  2. Number(value) semantics
  3. empty text becomes zero
  4. bounds do the real rejecting

basics

~20 s

z.coerce.number() runs Number(input), then the usual finite-number check. "42" becomes 42 and "abc" fails as NaN, but "" becomes 0 and passes, as do " 7 ", "1e3" and "0x1F", so bounds like .int().min(1) must do the rejecting.

solid answer

~40 s

`z.coerce.number()` is `z.number()` with one step in front: it calls JavaScript's `Number(input)` and then applies the normal check that the result is a finite number. So `"42"` becomes `42`, and `"abc"` becomes `NaN` and fails with `invalid_type`. The trap is what `Number()` accepts silently: an empty or whitespace-only string becomes `0`, surrounding spaces are ignored, and `"1e3"` and `"0x1F"` become `1000` and `31`. On a search endpoint, `page` should therefore be `z.coerce.number().int().min(1)` and `pageSize` should add a `.max()`, because the bounds, not the coercion, reject `?page=`. In Zod 4 every coerced schema's input type is `unknown`, and `z.coerce.date()` follows the same pattern with `new Date(value)`, which has quirks of its own.

code

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

const SearchQuery = z.object({
  page: z.coerce.number().int().min(1),
  pageSize: z.coerce.number().int().min(1).max(100),
  since: z.iso.date().optional(),
});

SearchQuery.safeParse({ page: "2", pageSize: "50" }).success;   // true: page 2, pageSize 50
SearchQuery.safeParse({ page: "", pageSize: "50" }).success;    // false: "" became 0, which fails .min(1)
SearchQuery.safeParse({ page: "abc", pageSize: "50" }).success; // false: NaN, invalid_type
SearchQuery.safeParse({ page: "1e1", pageSize: "50" }).success; // true: page is 10
SearchQuery.safeParse({ page: "1", pageSize: "50", since: "2024-02-30" }).success; // false: not a real date

go deeper

for a junior

Recall that z.coerce.number() calls Number() on the input and then checks for a finite number, so "abc" fails while "42" passes.

for a middle

Walk through the silent cases, empty text to 0, whitespace, exponent and hex notation, and show which int, min and max bounds catch each one.

for a senior

Decide per input source: coerce only what can only be text, keep strict numbers for JSON bodies, and check date text with an ISO format before converting it.

for a principal

Argue for a team rule that coercion appears only at text boundaries and is always followed by bounds, so lenient conversion never becomes an unstated contract.

## What z.coerce is Zod's primitive schemas normally check a value's type without converting it. The `z.coerce` namespace gives you variants that **convert first, then check**. Each one calls a built-in JavaScript constructor on the input and hands the result to the ordinary schema: | Coerced schema | Conversion applied | Then checked as | |---|---|---| | `z.coerce.string()` | `String(value)` | a string | | `z.coerce.number()` | `Number(value)` | a finite number | | `z.coerce.boolean()` | `Boolean(value)` | a boolean | | `z.coerce.bigint()` | `BigInt(value)` | a bigint | | `z.coerce.date()` | `new Date(value)` | a valid `Date` | The order matters: conversion happens first, and every check you chain afterwards, such as `.int()`, `.min(1)` or `.max(100)`, runs on the converted number, not on the original text. That is what makes bounds useful after coercion. Coercion exists because some inputs can only ever be text. A query string such as `?page=2&pageSize=50` reaches your code as strings, and so do form fields and environment variables. A strict `z.number()` would reject every one of them. ## Walking a search query string Take a search endpoint whose query arrives as strings: `page`, `pageSize` and `since`. Here is what `z.coerce.number()` does with typical values: | Query text | `Number(text)` | Result of `z.coerce.number()` | |---|---|---| | `"42"` | `42` | passes as `42` | | `"abc"` | `NaN` | fails, `invalid_type` | | `"12px"` | `NaN` | fails; `Number()` is not `parseInt()` | | `""` | `0` | **passes as `0`** | | `" "` | `0` | **passes as `0`** | | `" 7 "` | `7` | passes; spaces are ignored | | `"1e3"` | `1000` | passes; exponent notation is accepted | | `"0x1F"` | `31` | passes; hex notation is accepted | | `"Infinity"` | `Infinity` | fails; Zod 4 rejects infinite values | ## What slips through The failures are fine. The successes are the interview point, because each one is a value the client probably did not mean: - **Empty input becomes zero.** `?page=` parses as `page: 0`. Without a lower bound your pagination code receives a page number nobody asked for. - **Formatting is forgiven.** Leading and trailing whitespace, exponent notation and hex notation all produce numbers. - **Floats pass.** `"2.5"` becomes `2.5`, which is meaningless for a page number. - **Negative numbers pass.** `"-5"` becomes `-5`; nothing in `z.coerce.number()` knows that a page size must be positive. - **Non-strings convert too.** If the same schema ever sees `null` it becomes `0`, and `true` becomes `1`. The fix is to let the bounds carry the validation: `z.coerce.number().int().min(1)` rejects `0`, `2.5` and negative values, and `.max(100)` caps `pageSize`. ## Dates and bigints The other coercions have quirks of the same kind: - `z.coerce.date()` calls `new Date(value)`. An empty string or `"not a date"` gives an invalid `Date`, which fails. But `null` gives the Unix epoch and passes, a timestamp sent as text such as `"1712345678901"` gives an invalid `Date` and fails, and the engine's date parser may roll an impossible date forward instead of rejecting it: in Node, `new Date("2024-02-30")` is 1 March. - A safer pattern for `since` is to check the text's shape first with `z.iso.date()` or `z.iso.datetime()`, which reject `2024-02-30`, and convert afterwards. - `z.coerce.bigint()` calls `BigInt(value)`. Text such as `"abc"` makes `BigInt()` throw; Zod catches that and reports `invalid_type`. An empty string, however, becomes `0n`. ## What Zod 4 changed Two coercion details changed in Zod 4: 1. **The input type is `unknown`.** In Zod 3 a coerced schema's input type matched its output, for example `string` for `z.coerce.string()`. In Zod 4, `z.input<typeof z.coerce.number()>` is `unknown`, because any value is a legal input to `Number()`. Pass a generic to narrow it: `z.coerce.number<string>()`. 2. **A missing key now fails.** Inside an object schema, an absent key under a required coerced field fails rather than being coerced from `undefined`; Zod 3 could turn a missing `z.coerce.boolean()` key into `false`. Declare `.optional()` or an explicit `.default()` when a parameter may be omitted. ## A hardened schema 1. Coerce only fields that can only be text. 2. Follow every numeric coercion with `.int()` and the bounds the contract states. 3. Validate date text with an ISO format schema before converting it. 4. Keep strict `z.number()` for JSON bodies, where coercion would quietly accept `"42"`, `""` or `true`.

  • Should a numeric field in a JSON request body use z.coerce.number() in Zod 4?
    Usually not. A JSON body already carries real numbers, so `z.number()` is the right check. Coercion there would quietly accept `"42"`, `""`, `true` or `null` as numbers (`true` becomes `1`, `null` becomes `0`). Keep coercion for inputs that can only be text: query strings, path parameters, form data and environment variables.
  • How do you narrow the input type of a Zod 4 coerced schema that is typed as unknown?
    Pass a generic parameter: `z.coerce.number<string>()` makes the input type `string` while the output stays `number`. Zod 4 types coerced inputs as `unknown` by default because `Number()` accepts anything; narrowing is useful when a function signature or form state should only offer text.
  • What happens in Zod 4 when a required coerced field's key is missing from the parsed object?
    Parsing fails with an issue at that key; Zod 4 does not coerce `undefined` into a value. That differs from Zod 3, where `z.coerce.boolean()` could turn a missing key into `false`. If a parameter may be omitted, say so with `.optional()` or declare the fallback with `.default()`.

  • z.coerce.number() rejects an empty string because it is not a number
  • z.coerce.number() uses parseInt, so "12px" becomes 12
  • Coercion makes .int() and .min() unnecessary on query parameters
  • z.coerce.date() always rejects impossible dates like 2024-02-30
  • Use z.coerce.number() on JSON body fields to be safe

Assumes Zod 4; coerced schemas now have input type unknown, and a missing key under a coerced field fails instead of being coerced from undefined.