Request Validation
- Validation
- Node.js
- Express
Checking that incoming data has the expected shape and content before acting on it, so bad input is rejected early with a clear error.
What you'll understand
- Why every server must validate incoming data
- The difference between validation and business rules
- How to reject bad input clearly and early
Explanation
Request validation is checking that incoming data has the shape and content your server expects before you act on it. Clients can send anything: missing fields, wrong types, or malicious values, so the server must never trust input. Validation is the boundary that keeps bad data out of your logic and your database.
Validation is about form: is email present, is it a string, does it look like an email, is age a positive number. It is separate from business rules, which are about meaning, such as whether an email is already registered. Do form validation first and fast; it is cheap and catches most bad requests before they reach your database.
When validation fails, reject the request with a 400 Bad Request and a message that says what was wrong, so the client can fix it. Validating early also improves security, because many vulnerabilities start with input the server should have rejected.
Examples
This TypeScript example validates a request body against a schema using zod and returns 400 when it does not match:
import { z } from 'zod';
const CreateUser = z.object({
email: z.string().email(),
age: z.number().int().positive(),
});
app.post('/users', (req, res) => {
const result = CreateUser.safeParse(req.body);
if (!result.success) {
return res.status(400).json({ message: 'Invalid input' });
}
// result.data is now typed and safe to use
});Common mistakes
- Trusting client input because the interface already validated it. The interface can be bypassed.
- Validating with scattered if-checks that are easy to forget; prefer one schema per input.
- Returning 500 for bad input; a client mistake is a 400.
- Mixing form validation with business rules, which makes both harder to follow.
Best practices
- Validate every external input at the boundary, before using it.
- Describe the expected shape in one schema and reject anything that does not match.
- Return 400 with a helpful message for invalid input.
- Keep form validation separate from business-rule checks.
Further reading
- OWASP, Input Validation Cheat Sheet — https://cheatsheetseries.owasp.org/cheatsheets/Input_Validation_Cheat_Sheet.html