Input Validation
Input validation means checking the data a client sends to your Express API before you use it. Never assume a request body has the fields you expect, in the right types and sizes. A good API validates every incoming request, rejects bad data with a 400 Bad Request response and a clear message, and only then saves or processes the input.
Why the server must validate
Frontend validation improves user experience, but anyone can bypass it by calling your API directly with Postman or curl. Without server-side checks, missing fields end up as undefined in your database, huge strings fill your storage, and wrongly typed values crash your code later. Validation at the API boundary keeps the rest of your application simple, because it can trust the data it receives.
Validating by hand
For one or two fields, a few if statements work. Check the value exists, has the right type, and fits the rules, and return early with status 400 if it does not.
app.post("/api/genres", (req, res) => {
const { name } = req.body;
if (typeof name !== "string" || name.trim().length < 3) {
return res
.status(400)
.json({ error: "name is required and must be at least 3 characters" });
}
// safe to use name here
});
Using a schema library
Manual checks get long and repetitive as fields multiply. Schema libraries such as Joi, Zod or express-validator let you describe the shape of valid data once and test any object against it. Here is the Joi version, which also covers several fields:
const express = require("express");
const Joi = require("joi");
const app = express();
app.use(express.json());
const studentSchema = Joi.object({
name: Joi.string().trim().min(3).max(50).required(),
email: Joi.string().email().required(),
age: Joi.number().integer().min(16).max(99),
});
app.post("/api/students", (req, res) => {
const { error, value } = studentSchema.validate(req.body, {
abortEarly: false,
});
if (error) {
const messages = error.details.map((d) => d.message);
return res.status(400).json({ errors: messages });
}
// value contains the cleaned data (trimmed, converted)
res.status(201).json({ id: Date.now(), ...value });
});
The option abortEarly: false collects every problem instead of stopping at the first, so the client can show all errors at once. The returned value is the validated and converted data, so prefer it over the raw req.body.
Reusing the schema
Create and update routes usually need the same rules. Put the schema in its own function or module, for example validateStudent(body), and call it from both the POST and PUT handlers. When a rule changes, you change it in one place. Some teams wrap this in a small middleware that validates and calls next() only when the data passes.
Mistakes that let bad data through
Forgetting the return when sending the 400 response is the classic bug. Without it, the handler keeps running after the error response, tries to save the invalid data, and then attempts to send a second response, which crashes with "Cannot set headers after they are sent to the client".
Another common weakness is accepting unknown fields. If a client sends "isAdmin": true and you spread req.body straight into a database record, the user may grant themselves extra rights. Joi rejects unknown keys by default; keep that behaviour, or pick only the fields you expect.
Finally, remember that query strings and URL parameters are always strings. Validate and convert req.params.id too, not just the body.
Takeaway: validate every request on the server, return a 400 with useful messages, use a schema library once rules grow, always return after sending an error, and never trust extra fields.
Ready to master real-world web development?
Learn HTML, CSS3, Bootstrap and JavaScript hands-on with mentor-led sessions.