Pre-parse coercion
Convert form, query-string, or environment-variable values into a validated primitive.
Zod · Module
z.preprocess() transforms raw input before passing it to another Zod schema for validation. It is useful for custom normalization or coercion, while straightforward primitive coercion can use Zod's dedicated coercion APIs.
z.preprocess() creates a schema that runs a preprocessing function on the input first, then feeds the result into the supplied schema for validation. Its input type is unknown by default because the function may receive arbitrary values; annotate the function parameter when you need a narrower input type.
z.preprocess(preprocess, schema)| Name | Type | Description |
|---|---|---|
preprocess | (value: unknown) => unknown | Function that receives the raw input and returns the value to be parsed by the target schema. |
schema | z.ZodType | Schema that validates the value returned by the preprocessing function. |
A schema that preprocesses its input and then validates the resulting value with the supplied schema; in current Zod it is represented by a ZodPipe.
z.input to inspect or expose the input type accepted by a preprocessing schema.z.output to inspect the type produced after preprocessing and validation.unknown unless the preprocessor parameter is explicitly annotated.import { z } from "zod";
const coercedInt = z.preprocess((value) => {
if (typeof value === "string") return Number.parseInt(value, 10);
return value;
}, z.int());
console.log(coercedInt.parse("42")); // 42The preprocessor converts string input to a number before the integer schema validates it.
Convert form, query-string, or environment-variable values into a validated primitive.
Normalize nullable or loosely shaped input before applying a strict schema.
Accept a wider external input type while exposing a precise parsed output type.
z.preprocess() do?z.preprocess() applies a function before the destination schema parses the value. This is useful when input must be normalized or coerced before validation, such as converting a numeric string into an integer.
Follow-up: How can the input type be narrowed? Annotate the preprocessor parameter, then use z.input<typeof schema> to obtain the narrowed input type.
The preprocessor receives arbitrary input by default, so the schema's input type is unknown. The output type comes from the schema passed as the second argument.
Follow-up: What are the corresponding type helpers? z.input<typeof schema> describes the accepted input, while z.output<typeof schema> describes the parsed result.
It is useful when a transformation must happen before validation rather than after it. The transformed value is then checked by the target schema, such as z.int() in a string-to-number conversion.
Follow-up: When should primitive coercion be used instead? Use Zod's primitive coercion support for straightforward primitive conversions; reserve preprocessing for custom preparation logic.
z.coercez.pipez.transformz.inputz.output