Concept Explanation
Every piece of data arriving at your server — form fields, URL params, JSON bodies — comes from the outside world, and the outside world lies. A user might send a negative age, a missing email, or a giant string designed to crash you. Validation is the bouncer at the door: it checks every request before your real logic runs and rejects anything malformed.
The golden rule of backend security: never trust the client. Frontend validation is a convenience for honest users; server validation is what actually protects you.
Syntax or Core Structure
You can check by hand:
app.post("/signup", (req, res) => {
const { email, age } = req.body;
if (!email || !email.includes("@")) {
return res.status(400).json({ error: "Invalid email" });
}
if (typeof age !== "number" || age < 0) {
return res.status(400).json({ error: "Invalid age" });
}
// ...safe to continue
});
But most teams use a schema library like Zod or Joi:
const schema = z.object({
email: z.string().email(),
age: z.number().min(0)
});
const result = schema.safeParse(req.body); // valid, or a list of errors
Common Mistakes
- Trusting the Frontend: Client checks are trivially bypassed with a tool like curl. Always re-validate on the server.
- Validating Only the Body: URL params and query strings need checking too (
/users/abcwhere a number was expected). - Vague Errors: "Invalid input" frustrates users. Say which field failed and why.
Best Practices
- Validate at the Edge: Check input in middleware before it touches your business logic.
- Whitelist, Don't Blacklist: Define exactly what's allowed rather than trying to list everything banned.
- Return 400 with Detail: A structured list of field errors helps the frontend show good messages.
Practice Exercises
- The Guard: Write a route that rejects a signup missing an
emailfield with a400. - The Schema: Recreate the validation above using Zod (or plain
ifchecks) for a "product" with a name and a positive price. - The Bypass: Use curl (or Postman) to send invalid data straight to your server and confirm your validation still blocks it.