Why does a Zod 4 search schema that declares active as z.coerce.boolean() turn the query value active=false into true, and what should replace it?
answer
- JavaScript truthiness, not meaning
- any non-empty string is truthy
- an explicit truthy and falsy list
- unlisted text is rejected
basics
~20 sz.coerce.boolean() calls Boolean(input), and every non-empty string, "false" included, is truthy, so it becomes true. Replace it with z.stringbool(), added in Zod 4.0, which maps listed words such as "false", "0" and "no" to false and rejects unlisted text.
solid answer
~40 s`z.coerce.boolean()` applies JavaScript's `Boolean(value)`: truthy values become `true`, falsy ones `false`. Every non-empty string is truthy, so `"false"`, `"0"` and `"no"` all become `true`; only the empty string becomes `false`. The schema never fails on a string, so the bug ships quietly. Zod 4.0 added `z.stringbool()` for this case: it lowercases the input, maps `"true"`, `"1"`, `"yes"`, `"on"`, `"y"` and `"enabled"` to `true` and `"false"`, `"0"`, `"no"`, `"off"`, `"n"` and `"disabled"` to `false`, and rejects anything else with an `invalid_value` issue. The `truthy` and `falsy` options replace the lists, and `case: "sensitive"` turns off lowercasing. It expects a string, so keep plain `z.boolean()` for JSON bodies, where a real `true` would fail `z.stringbool()`.
code
typescript · 16 linesimport * as z from "zod";
const loose = z.coerce.boolean();
loose.parse("false"); // true
loose.parse("0"); // true
loose.parse(""); // false
const flag = z.stringbool();
flag.parse("false"); // false
flag.parse("No"); // false (matching is case-insensitive by default)
flag.parse("1"); // true
flag.safeParse("maybe").success; // false: invalid_value
flag.safeParse(true).success; // false: the input must be a string
const strictFlag = z.stringbool({ truthy: ["true"], falsy: ["false"], case: "sensitive" });
strictFlag.safeParse("TRUE").success; // falsego deeper
Recall that z.coerce.boolean() uses JavaScript truthiness, so "false" becomes true, and that z.stringbool() is the Zod 4 schema for boolean text.
Explain the default truthy and falsy word lists, the case-insensitive matching, the invalid_value issue for unlisted text, and the truthy, falsy and case options.
Show how you would find every coerced boolean that reads text, swap in z.stringbool(), and add tests for both spellings and for a rejected value.
Use the bug as a reason to review every lenient conversion: decide which spellings the public contract promises and make each schema enforce exactly those.
## The symptom A search endpoint reads its filters from the query string: `?page=1&active=false`. Every value arrives as text, so the schema author reached for Zod's coercion namespace and wrote `active: z.coerce.boolean()`. Requests with `active=true` behave. Requests with `active=false` also return only active records. No validation error is ever raised, and the logs show `active: true` for both. ## Why Boolean() gets it wrong `z.coerce.boolean()` converts its input with JavaScript's built-in `Boolean(value)` and then checks that the result is a boolean, which it always is. `Boolean()` implements **truthiness**: it asks whether a value is "empty-ish", not what a word means. | Input | `Boolean(input)` | Comment | |---|---|---| | `"true"` | `true` | correct by coincidence | | `"false"` | `true` | non-empty string, so truthy | | `"0"` | `true` | non-empty string, so truthy | | `"no"` | `true` | non-empty string, so truthy | | `""` | `false` | the only falsy string | | `0`, `null`, `undefined` | `false` | falsy non-strings | Every non-empty string is truthy, so the only text that `z.coerce.boolean()` turns into `false` is the empty string. Because the conversion never fails, the schema cannot report the problem: this is a **silent** misparse, which is why it survives code review and happy-path tests. The same trap appears wherever booleans travel as text. An environment variable such as `FEATURE_ENABLED=false` read through `z.coerce.boolean()` switches the feature on, and a form checkbox posted as `"off"` counts as checked. In each case the schema author wanted a mapping from words to booleans and got a test for emptiness instead. ## z.stringbool() Zod 4.0 introduced `z.stringbool()` for exactly this job, parsing "boolish" text such as query flags and environment variables. Its behaviour: - **Default truthy words:** `"true"`, `"1"`, `"yes"`, `"on"`, `"y"`, `"enabled"`. - **Default falsy words:** `"false"`, `"0"`, `"no"`, `"off"`, `"n"`, `"disabled"`. - **Case-insensitive by default:** the input is lowercased before comparison, so `"False"` and `"NO"` work. - **Anything else fails** with an `invalid_value` issue rather than being guessed. - **Options:** `truthy` and `falsy` replace the word lists, and `case: "sensitive"` turns off lowercasing. - **String input only:** a value that is not a string fails the inner string check with `invalid_type`. Rejecting unlisted text is the important design choice. A client that sends `active=maybe` or a misspelt `active=flase` gets a validation error it can act on, instead of a filter silently applied the wrong way round. Lowercasing by default keeps `"True"` and `"FALSE"` working, which matches how people actually type flags into URLs and configuration files. Internally it is built as a codec from a string schema to a boolean schema, which also lets it encode a boolean back to text; the codec mechanics belong to the material on transforms and codecs. ## Where each schema belongs | Input source | Schema | Reason | |---|---|---| | Query string, form field, env var | `z.stringbool()` | the value is text and needs word mapping | | JSON request body | `z.boolean()` | JSON already carries real booleans | | Already-typed value, truthiness wanted | `z.coerce.boolean()` | only when truthiness really is the rule | The last row is rare. For text input `z.coerce.boolean()` is almost always the wrong tool, and in a JSON body `z.stringbool()` is wrong too, because the client sends `true`, not `"true"`. ## Debugging and fixing it 1. **Reproduce with the falsy spelling.** Send `active=false` and `active=0`; both come back `true`. 2. **Find every coerced boolean.** Search the codebase for `z.coerce.boolean(`; each hit that reads text has the same bug. 3. **Swap in `z.stringbool()`.** If the public contract documents only `true` and `false`, pin it: `z.stringbool({ truthy: ["true"], falsy: ["false"], case: "sensitive" })`. 4. **Handle absence explicitly.** In Zod 4 a missing key under a required field fails, so mark an optional flag with `.optional()` or give it a `.default()`. 5. **Add regression tests** for both directions and for a rejected value such as `"maybe"`. ## Version note `z.stringbool()` does not exist in Zod 3, where teams hand-rolled the mapping with a transform. In Zod 4 it is a first-class schema in the main `zod` package. Zod 3 also coerced a missing key under `z.coerce.boolean()` into `false`; Zod 4 reports the missing key instead.
- Why did the Zod 4 z.coerce.boolean() bug survive tests that sent ?active=true?Because `"true"` really does become `true` under `Boolean()`, so the happy path looks right. Only a test that sends the falsy spelling clients use, such as `"false"` or `"0"`, exposes it. A good regression test for each boolean query flag asserts both directions and asserts that an unrecognised value such as `"maybe"` is rejected.
- How do you make Zod 4's z.stringbool() accept only the exact words "true" and "false"?Pass your own lists and turn off case folding: `z.stringbool({ truthy: ["true"], falsy: ["false"], case: "sensitive" })`. Then `"TRUE"`, `"1"` and `"yes"` all fail with `invalid_value`, which suits a public contract that documents only those two spellings.
z.coerce.boolean() is a doorman who admits anyone holding any piece of paper, even one that reads "not admitted". z.stringbool() actually reads the paper, and turns away anything it cannot read.
- z.coerce.boolean() understands the words "false" and "0"
- z.stringbool() also accepts a JSON boolean true
- z.stringbool() is case-sensitive by default
- A boolean query flag is fine once ?flag=true works
- z.stringbool() maps unrecognised text to false
Assumes Zod 4; z.stringbool() was introduced in Zod 4.0, so Zod 3 code has to hand-roll the word mapping.