API Request Validation with Zod: The Schema That Catches Bad Input Before It Corrupts Your Database
A malformed request slipped past JSON parsing and wrote a null into a required column, causing a cascade of 500s that took two hours to clean up. Here is the Zod validation layer that stops bad input at the API boundary, with the TypeScript integration, custom refinements, and error formatting that makes client integrations painless.
The checkout endpoint had run in production for eight months without a single schema-related incident. Then a partner integration changed their payload format silently. Instead of quantity: 2, they sent quantity: "2". Instead of metadata: null or an object, they sent metadata: undefined. The route handler used req.body.quantity * req.body.price, which in JavaScript evaluates "2" * 19.99 to 39.98 correctly. But the ORM insert mapped metadata: undefined to DEFAULT in SQL, which for that column meant null. A downstream reporting job that expected metadata to be either a valid object or absent entirely choked on the batch insert, threw an unhandled rejection, and the worker restarted in a loop. Two hours of dirty data cleanup. One line of validation would have caught it in 2 milliseconds.
This post is not an introduction to Zod. It is a production-grade validation layer for Express (or Fastify, or Hono) that stops malformed, mistyped, and malicious input before it touches your business logic or your database. We will build the schema, the middleware, the custom refinements, and the error response format that clients actually understand.
Why JSON parsing is not validation
express.json() does one thing: it turns a JSON string into a JavaScript object. It has no opinion on whether userId is a UUID, whether email contains an @, or whether quantity is a positive integer. Worse, every property is implicitly optional from TypeScript’s perspective if you cast the body:
app.post('/orders', async (req, res) => {
const body = req.body as CreateOrderBody; // TypeScript trusts you. The runtime does not.
const total = body.quantity * body.price; // NaN if either is a string that is not numeric
});
The as keyword tells TypeScript “I guarantee this shape.” The runtime guarantees nothing. A missing field becomes undefined. A wrong type stays the wrong type. A string where you expected a number stays a string until some arithmetic operation silently coerces it or produces NaN.
The fix is not “add manual if-checks everywhere.” That leads to 400-line route handlers and inconsistent error messages. The fix is a single source of truth at the boundary: a schema that describes exactly what the API accepts, with types, constraints, and transforms, enforced before the handler runs.
The schema: stricter than TypeScript
Here is the Zod schema for a checkout endpoint. It is stricter than the TypeScript interface because it enforces runtime rules that TypeScript cannot express.
import { z } from 'zod';
const OrderItemSchema = z.object({
sku: z.string().min(1).max(64),
quantity: z.number().int().positive().max(10_000),
price: z.number().positive().max(1_000_000),
});
const CreateOrderSchema = z.object({
userId: z.string().uuid(),
email: z.string().email().max(254),
items: z.array(OrderItemSchema).min(1).max(50),
shippingAddress: z.object({
line1: z.string().min(1).max(128),
line2: z.string().max(128).optional(),
city: z.string().min(1).max(64),
country: z.string().length(2), // ISO-3166 alpha-2
postalCode: z.string().min(3).max(16),
}),
metadata: z.record(z.string(), z.unknown()).optional(),
couponCode: z.string().max(32).optional(),
});
type CreateOrderBody = z.infer<typeof CreateOrderSchema>;
Note the difference between the TypeScript type and the Zod schema. The type says quantity is a number. The schema says it is an integer, positive, and no larger than 10,000. The type says userId is a string. The schema says it must be a valid UUID. The type says email is a string. The schema says it must contain an @ and a domain, and fit in 254 characters.
The z.infer<typeof CreateOrderSchema> line is the critical integration point. You never write the TypeScript type by hand. You derive it from the schema. If the schema changes, the type changes automatically. There is no drift between what TypeScript thinks the shape is and what the runtime actually validates.
The middleware: one line per route
The goal is to validate once, early, and fail with a structured error that the client can parse without regex.
import type { Request, Response, NextFunction } from 'express';
function validateBody<T>(schema: z.ZodType<T>) {
return (req: Request, res: Response, next: NextFunction) => {
const result = schema.safeParse(req.body);
if (!result.success) {
return res.status(400).json({
error: 'ValidationError',
message: 'Request body does not match the expected schema',
details: result.error.issues.map((issue) => ({
path: issue.path.join('.'),
code: issue.code,
message: issue.message,
})),
});
}
req.body = result.data; // Replace the raw body with the parsed, typed object
next();
};
}
The middleware uses safeParse instead of parse so that validation errors do not throw exceptions. It formats Zod’s ZodIssue array into a flat, client-friendly structure. It replaces req.body with the parsed data, which means transforms (like string-to-number coercion) are applied and the handler downstream sees the clean value.
Usage is one line:
app.post('/orders', validateBody(CreateOrderSchema), async (req, res) => {
const body: CreateOrderBody = req.body; // Fully typed, fully validated
// ... business logic
});
If the partner integration sends quantity: "2", the middleware responds with a 400 before the handler runs. The error details tell the client exactly which field failed and why:
{
"error": "ValidationError",
"message": "Request body does not match the expected schema",
"details": [
{ "path": "items.0.quantity", "code": "invalid_type", "message": "Expected number, received string" }
]
}
Query and parameter validation
Body validation is the obvious place to start, but most injection and routing bugs come from query strings and URL parameters. They are strings by definition, and developers often parse them with parseInt(req.query.page) which returns NaN on bad input and does not surface an error to the client.
const ListOrdersQuerySchema = z.object({
page: z.coerce.number().int().positive().default(1),
limit: z.coerce.number().int().positive().max(100).default(20),
status: z.enum(['pending', 'paid', 'shipped', 'cancelled']).optional(),
sort: z.enum(['createdAt', 'total']).default('createdAt'),
userId: z.string().uuid().optional(),
});
The z.coerce.number() transform is the key detail. It takes whatever string arrives from the query parameter and attempts to coerce it to a number. If the client sends ?page=abc, coercion fails and Zod reports invalid_type with a 400. If they send ?page=2, they get the number 2. The default values mean the handler never sees undefined for optional fields; it sees 1 and 20.
A similar helper for query validation:
function validateQuery<T>(schema: z.ZodType<T>) {
return (req: Request, res: Response, next: NextFunction) => {
const result = schema.safeParse(req.query);
if (!result.success) {
return res.status(400).json({
error: 'ValidationError',
message: 'Query parameters do not match the expected schema',
details: result.error.issues.map((issue) => ({
path: issue.path.join('.'),
code: issue.code,
message: issue.message,
})),
});
}
req.query = result.data as any;
next();
};
}
Custom refinements for business logic
Zod’s built-in checks cover type, length, and format. Business rules need custom refinements: a coupon that is only valid on Tuesdays, a shipping address that must be domestic for same-day delivery, an order total that cannot exceed $50,000.
const BusinessOrderSchema = CreateOrderSchema.superRefine((data, ctx) => {
const total = data.items.reduce((sum, item) => sum + item.quantity * item.price, 0);
if (total > 50_000) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: `Order total ${total} exceeds maximum allowed value of 50000`,
path: ['items'],
});
}
const domesticCountries = ['US', 'CA', 'MX'];
if (data.couponCode?.startsWith('SAME_DAY') && !domesticCountries.includes(data.shippingAddress.country)) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: 'Same-day coupon is only valid for domestic shipping',
path: ['couponCode'],
});
}
});
superRefine runs after the base schema passes, so you know items is an array of valid objects before you compute the total. The ctx.addIssue API attaches errors to specific paths, so the client sees items or couponCode as the failing field, not a generic top-level error.
This is where validation becomes more than type safety. It is business-rule enforcement at the boundary. The database never sees an order over $50,000 because the API rejects it in the middleware layer.
A reusable factory for all routes
Copy-pasting validateBody, validateQuery, and validateParams into every route file gets old. A small factory cleans it up:
import { z } from 'zod';
import type { Request, Response, NextFunction } from 'express';
export function createValidator<TBody, TQuery, TParams>(schemas: {
body?: z.ZodType<TBody>;
query?: z.ZodType<TQuery>;
params?: z.ZodType<TParams>;
}) {
return (req: Request, res: Response, next: NextFunction) => {
const errors: Array<{ path: string; code: string; message: string }> = [];
if (schemas.body) {
const result = schemas.body.safeParse(req.body);
if (!result.success) {
errors.push(...result.error.issues.map((i) => ({
path: `body.${i.path.join('.')}`,
code: i.code,
message: i.message,
})));
} else {
req.body = result.data;
}
}
if (schemas.query) {
const result = schemas.query.safeParse(req.query);
if (!result.success) {
errors.push(...result.error.issues.map((i) => ({
path: `query.${i.path.join('.')}`,
code: i.code,
message: i.message,
})));
} else {
req.query = result.data as any;
}
}
if (schemas.params) {
const result = schemas.params.safeParse(req.params);
if (!result.success) {
errors.push(...result.error.issues.map((i) => ({
path: `params.${i.path.join('.')}`,
code: i.code,
message: i.message,
})));
} else {
req.params = result.data as any;
}
}
if (errors.length > 0) {
return res.status(400).json({
error: 'ValidationError',
message: 'Request does not match the expected schema',
details: errors,
});
}
next();
};
}
Now a route definition reads like a schema document:
app.post(
'/orders',
createValidator({ body: BusinessOrderSchema }),
async (req, res) => {
const body = req.body as z.infer<typeof BusinessOrderSchema>;
const order = await createOrder(body);
res.status(201).json(order);
}
);
app.get(
'/orders',
createValidator({ query: ListOrdersQuerySchema }),
async (req, res) => {
const query = req.query as z.infer<typeof ListOrdersQuerySchema>;
const orders = await listOrders(query);
res.json(orders);
}
);
Performance: validation is not free, but it is cheap
A common objection is “we cannot afford to validate every request.” In practice, Zod validation of a typical JSON body takes 0.1 to 0.5 milliseconds on a modern CPU. Compare that to a single Postgres round-trip at 2 milliseconds, a Redis call at 1 millisecond, or the time it takes to JSON.stringify a response. Validation is the cheapest operation in the request path, and it saves the most expensive ones (database writes, downstream calls, error remediation) from processing garbage.
If you are truly at the scale where 0.2ms matters, Zod supports precompilation. The zod-to-json-schema package can compile a Zod schema to a JSON Schema, and ajv can validate against it at roughly twice the speed. But measure first. Most APIs will never notice the difference.
The production checklist
Before you ship the validation layer, verify these five things.
-
All public routes have a schema. Internal routes and health checks can skip it, but any route that accepts a body, query, or params from a client needs validation. Audit your router file; if a route is missing
createValidator, that is a bug. -
Error responses are documented. Clients need to know that a 400 response contains
{ error: 'ValidationError', details: [...] }. Put it in your API documentation. If you use OpenAPI, generate the error response schema from the Zod types. -
Do not leak internal structure. Never return
result.error.messagedirectly from Zod. It can contain internal schema details. Always map to a controlled format like thedetailsarray above. -
Log validation failures at warn level. A spike in 400s is often the first sign of a broken client integration or an attempted injection attack. Log the route, the IP, and the error codes (not the full payload if it contains PII).
-
Keep schemas close to the route. Do not define all schemas in a single
schemas.tsfile three directories away from the handler. Colocate the schema with the route file, or in aschemas.tssibling file in the same directory. When the route changes, the schema is right there.
The takeaway
TypeScript is a compile-time guard. It disappears at runtime. express.json() is a transport parser. It has no opinion on shape. The gap between them is where bad input becomes data corruption, NaN bugs, and two-hour cleanup sessions.
Zod closes that gap with a schema that is both the TypeScript type and the runtime validator. One source of truth. One line of middleware per route. Custom refinements for business rules. Structured errors that clients parse without guessing.
Start with the body schemas on your write endpoints. Add query validation next. Add refinements for the invariants that should never reach the database. The first malformed payload that gets a 400 instead of a corrupted row will pay for the entire migration.
A note from Yojji
The kind of defensive API design that validates every input at the boundary, formats errors for client integrations, and keeps business rules out of the database layer is exactly the kind of engineering rigor Yojji’s teams bring to the products they build.
Yojji is an international custom software development company founded in 2016, with teams across Europe, the US, and the UK. They specialize in the JavaScript ecosystem (React, Node.js, TypeScript), cloud platforms (AWS, Azure, GCP), and full-cycle product engineering, including the API architecture and validation patterns that keep production systems stable when client behavior changes.