Input Validation
All input is untrusted: body, query, params, headers, cookies, files, webhooks, even data from your own frontend.
Rules
- Validate type, length, format, range at the API boundary.
- Use an allowlist (what is allowed), not a blocklist (what is banned).
- Reject unknown fields.
- Validate on the server even if the frontend already did.
Packages
| Package | Use |
|---|---|
zod | Schema validation with TypeScript types (recommended) |
joi | Schema validation (popular in Express/Hapi) |
express-validator | Validation middleware for Express |
validator | String checks (isEmail, isURL…) |
hpp | Blocks HTTP parameter pollution (?role=a&role=b) |
❌ Vulnerable
app.post('/users', async (req, res) => {
await User.create(req.body); // any field, any type, any size
});✅ Secure (zod)
const { z } = require('zod');
const CreateUser = z.object({
email: z.string().email().max(254),
name: z.string().trim().min(1).max(100),
age: z.number().int().min(13).max(120).optional(),
}).strict(); // reject unknown fields like "role"
const validate = (schema) => (req, res, next) => {
const result = schema.safeParse(req.body);
if (!result.success) return res.status(400).json({ errors: result.error.flatten() });
req.body = result.data;
next();
};
app.post('/users', validate(CreateUser), async (req, res) => {
await User.create(req.body);
res.status(201).end();
});Also limit request size
app.use(express.json({ limit: '100kb' })); // stops huge payloadsChecklist
- A schema for every endpoint (body, query, params)
-
.strict()/ reject unknown keys - Max lengths on every string, max size on arrays
- Body size limit
- Validate webhook payloads and verify their signatures