typescript
44 lines · 8 steps
Validating URL query params with Zod
A Zod schema coerces, defaults, and reshapes raw query strings into a typed product query object.
Explained by
highlit
1import { z } from "zod";
2
3const ProductQuerySchema = z.object({
4 page: z.coerce.number().int().positive().default(1),
5 perPage: z.coerce.number().int().min(1).max(100).default(20),
6 sort: z.enum(["price_asc", "price_desc", "newest"]).default("newest"),
7 inStock: z
8 .enum(["true", "false"])
9 .transform((v) => v === "true")
10 .optional(),
11 minPrice: z.coerce.number().nonnegative().optional(),
12 maxPrice: z.coerce.number().nonnegative().optional(),
13 tags: z
14 .union([z.string(), z.array(z.string())])
15 .transform((v) => (Array.isArray(v) ? v : [v]))
16 .pipe(z.array(z.string().min(1)))
17 .optional(),
18});
19
20export type ProductQuery = z.infer<typeof ProductQuerySchema>;
21
22export function parseProductQuery(raw: URLSearchParams): ProductQuery {
23 const grouped: Record<string, string | string[]> = {};
24 for (const key of new Set(raw.keys())) {
25 const values = raw.getAll(key);
26 grouped[key] = values.length > 1 ? values : values[0];
27 }
28
29 const result = ProductQuerySchema.safeParse(grouped);
30 if (!result.success) {
31 const issues = result.error.issues.map((i) => ({
32 field: i.path.join("."),
33 message: i.message,
34 }));
35 throw new BadRequestError("Invalid query parameters", issues);
36 }
37
38 const { minPrice, maxPrice } = result.data;
39 if (minPrice != null && maxPrice != null && minPrice > maxPrice) {
40 throw new BadRequestError("minPrice cannot exceed maxPrice");
41 }
42
43 return result.data;
44}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Coercion plus defaults let a schema accept messy string input and emit clean, typed values.
- 2Deriving a TypeScript type from the schema keeps runtime validation and compile-time types in sync.
- 3Cross-field rules that a schema can't express belong in a follow-up check after parsing.
Related explainers
typescript
import { registerLocaleData } from '@angular/common'; import localeFr from '@angular/common/locales/fr'; import localeFrExtra from '@angular/common/locales/extra/fr'; import localeDe from '@angular/common/locales/de';
Locale-aware bootstrapping in Angular
i18n
localization
dependency-injection
Intermediate
8 steps
typescript
import { Module } from '@nestjs/common'; import { ConfigModule } from '@nestjs/config'; import * as Joi from 'joi';
Validating env config at boot in NestJS
configuration
schema-validation
environment-variables
Intermediate
8 steps
php
<?php namespace App\Services\Checkout;
Validating coupons with Laravel's Pipeline
pipeline
chain of responsibility
transactions
Intermediate
7 steps
typescript
import { Inject, Injectable, Logger } from '@nestjs/common'; import { CACHE_MANAGER } from '@nestjs/cache-manager'; import { Cache } from 'cache-manager'; import { InjectRepository } from '@nestjs/typeorm';
A cache-aside country lookup in NestJS
cache-aside
dependency-injection
batch-lookup
Intermediate
8 steps
php
<?php namespace App\Services;
How a password strength validator works in PHP
validation
regular-expressions
data-driven
Intermediate
8 steps
typescript
import { Injectable, effect, signal, computed } from '@angular/core'; interface Preferences { theme: 'light' | 'dark';
A signal-based preferences store in Angular
signals
state-management
persistence
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/validating-url-query-params-with-zod-explained-typescript-5cca/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.