Zod Transform and Coerce Pipeline
Coerce and transform incoming strings inside a Zod schema so trimming, defaults, and type conversion happen in one validated step.
Code
import { z } from "zod";
export const QuerySchema = z.object({
page: z.coerce.number().int().min(1).catch(1),
pageSize: z.coerce.number().int().min(1).max(100).default(20),
tags: z
.string()
.transform((raw) => raw.split(",").map((s) => s.trim()).filter(Boolean))
.pipe(z.array(z.string().min(1)).max(10)),
sort: z.enum(["asc", "desc"]).default("asc"),
});
export type Query = z.infer<typeof QuerySchema>;
export function parseQuery(params: Record<string, string | undefined>) {
return QuerySchema.parse({
page: params.page,
pageSize: params.pageSize,
tags: params.tags ?? "",
sort: params.sort,
});
}How the code works
Zod Transform and Coerce Pipeline is built around the function parseQuery.
Reach for zod and what you get is z — that is the whole API contact area.
Caveats
- Plan for an install step:
zodis a real dependency, resolved by the package manager.
Applying it
The primary signature is export const QuerySchema =
QuerySchema is what another module would consume; nothing else here is load-bearing for callers.
Statements that matter
return QuerySchema.parse({
page: params.page,
pageSize: params.pageSize,
tags: params.tags ?? "",
sort: params.sort,
});
.transform((raw) => raw.split(",").map((s) => s.trim()).filter(Boolean))
.pipe(z.array(z.string().min(1)).max(10)),
sort: z.enum(["asc", "desc"]).default("asc"),
});
Interactive Tools for This Topic
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.Credit Card Brand DetectorIdentify the card network from a number's prefix and length, validate the Luhn checksum, and show a masked form and the issuer identification number.
FAQ
- Which packages must be installed first?
- Yes. The imports resolve to `zod`, which the package manager must provide.
Report a problem with this exampleOpens a pre-filled issue on GitHub.