Validating input
Overview
Every value that arrives in a request is untrusted. A legitimate client might have a bug; an attacker might send anything at all — missing fields, wrong types, giant strings, negative quantities, extra fields like "role": "admin". If that data flows into your business logic or database unchecked, you get crashes, corrupted data and security holes.
The solution is to validate at the boundary: check every request against a precise description of what’s allowed, before any other code sees it.
Why a schema library?
You could write checks by hand:
if (typeof req.body.title !== 'string' || req.body.title.length < 3) { … }
if (!['Beginner', 'Intermediate', 'Advanced'].includes(req.body.level)) { … }
// …dozens more lines, easy to get wrong, different in every handlerA schema describes the shape once, declaratively, and gives you parsing, validation and error messages for free. Zod is the most popular choice in the Node ecosystem (alternatives include Valibot, Yup, Joi, and AJV for JSON Schema).
npm install zodDefining a schema
import { z } from 'zod';
export const createUserSchema = z.object({
name: z.string().trim().min(1, 'Name is required').max(100),
email: z.email().toLowerCase(),
password: z.string().min(12, 'Use at least 12 characters'),
age: z.number().int().min(13).optional(),
role: z.enum(['learner', 'teacher']).default('learner'),
interests: z.array(z.string()).max(10).default([]),
});Schemas both check and transform: .trim() and .toLowerCase() clean values, .default() fills in missing ones.
Parsing
const result = createUserSchema.safeParse(req.body);
if (!result.success) {
console.log(result.error.issues);
// [{ path: ['email'], message: 'Invalid email address', code: 'invalid_format', … }]
} else {
const user = result.data; // validated, cleaned, with defaults applied
}schema.parse(data)returns the data or throws aZodError.schema.safeParse(data)returns{ success: true, data }or{ success: false, error }— easier to handle in middleware.
Always use result.data, not the original req.body. The parsed version is the trustworthy one.
Unknown fields are removed
By default, an object schema strips keys it doesn’t know:
createUserSchema.parse({ name: 'Asha', email: 'a@x.com', password: '…', isAdmin: true });
// → { name, email, password, role: 'learner', interests: [] } — isAdmin is goneThat protects against mass assignment, where an attacker adds fields like isAdmin or balance hoping your code copies req.body straight into the database. Use z.strictObject({…}) if you’d rather reject unknown keys with an error.
A validation middleware
Write it once and use it on every route:
// src/middleware/validate.js
import { HttpError } from '../errors.js';
export const validate = (schemas) => (req, res, next) => {
const details = [];
for (const part of ['params', 'query', 'body']) {
if (!schemas[part]) continue;
const result = schemas[part].safeParse(req[part]);
if (result.success) {
req.validated ??= {};
req.validated[part] = result.data;
} else {
for (const issue of result.error.issues) {
details.push({ in: part, path: issue.path.join('.'), message: issue.message });
}
}
}
if (details.length) return next(new HttpError(400, 'Validation failed', details));
next();
};coursesRouter.post(
'/',
validate({ body: createCourseSchema }),
async (req, res) => {
const course = await coursesService.create(req.validated.body);
res.status(201).location(`/courses/${course.id}`).json(course);
},
);Storing results on req.validated keeps the raw and validated values clearly separate.
Params and query strings
Path parameters and query values are always strings. z.coerce converts them before checking:
const idParams = z.object({
id: z.coerce.number().int().positive(),
});
const listQuery = z.object({
search: z.string().trim().max(100).optional(),
level: z.enum(['Beginner', 'Intermediate', 'Advanced']).optional(),
limit: z.coerce.number().int().min(1).max(100).default(20),
page: z.coerce.number().int().min(1).default(1),
});
coursesRouter.get('/', validate({ query: listQuery }), listCourses);
coursesRouter.get('/:id', validate({ params: idParams }), getCourse);Now req.validated.query.limit is a real number between 1 and 100 — even if the URL said ?limit=999999.
Updates: partial schemas
For PATCH, every field is optional. Build the field rules once, then combine them two ways:
const title = z.string().trim().min(3).max(120);
const level = z.enum(['Beginner', 'Intermediate', 'Advanced']);
const pricePaise = z.number().int().min(0);
export const createCourseSchema = z.object({
title,
level: level.default('Beginner'),
pricePaise,
});
export const updateCourseSchema = z
.object({ title, level, pricePaise })
.partial()
.refine((data) => Object.keys(data).length > 0, 'Send at least one field to update');Watch out for defaults in updates.
createCourseSchema.partial()looks tempting, but fields with.default()still get their default when missing — so an update that only changes the title would silently resetlevelto'Beginner'. Keep defaults out of update schemas.
.refine() adds custom rules that aren’t about a single field — “at least one field”, “end date after start date”, “passwords match”.
Validation vs business rules
Schemas check the shape of input: types, formats, lengths, ranges. Some rules need your database or current state — “this email isn’t registered yet”, “the course has seats left”, “you own this order”. Check those in your service layer, and return 409 Conflict or 403 Forbidden as appropriate.
Bonus: types and config
If you use TypeScript, z.infer<typeof createUserSchema> gives you the matching type for free. And the same tool validates configuration at start-up:
const env = z.object({
PORT: z.coerce.number().default(3000),
DATABASE_URL: z.url(),
JWT_SECRET: z.string().min(32),
}).parse(process.env);Validate everything that crosses a boundary: HTTP requests, webhook payloads, messages from queues, responses from third-party APIs, and environment variables. Inside the boundary, your code can trust its data.
Validate course creation
Write a Zod schema for creating a course: title (3–120 chars, trimmed), level (Beginner, Intermediate or Advanced, default Beginner), pricePaise (whole number ≥ 0), and optional tags (up to 5 non-empty strings). Then write a validate(schema) middleware that replaces req.body with the parsed data or responds 400 with field errors.
import { z } from 'zod';
export const createCourseSchema = z.object({
// your code here
});
export const validate = (schema) => (req, res, next) => {
// your code here
};import { z } from 'zod';
export const createCourseSchema = z.object({
title: z.string().trim().min(3).max(120),
level: z.enum(['Beginner', 'Intermediate', 'Advanced']).default('Beginner'),
pricePaise: z.number().int().min(0),
tags: z.array(z.string().trim().min(1)).max(5).optional(),
});
export const validate = (schema) => (req, res, next) => {
const result = schema.safeParse(req.body);
if (!result.success) {
return res.status(400).json({
error: {
message: 'Validation failed',
details: result.error.issues.map((i) => ({ path: i.path.join('.'), message: i.message })),
},
});
}
req.body = result.data;
next();
};Summary
- Never trust anything from a request: body, params, query and headers can all be wrong or malicious.
- Describe valid input with a schema (Zod is popular) and validate at the edge of your app.
safeParsereturns either typed, cleaned data or a list of issues with paths and messages.- Schemas strip unknown fields by default — which stops mass-assignment attacks.
- Use
z.coercefor query strings and params, which always arrive as strings.