Validation & Sanitization
Check that incoming data has the shape you expect before your code uses it, and clean out anything unsafe.
What is it?
A backend can never fully trust request data, even from your own frontend. Anyone can send a request, with any tool, not just your app. A number field might arrive as text, a required field might be missing, or a name field might hide HTML or a database command.
Validation checks that incoming data matches what your code expects: the right fields are present, with the right type and shape. Sanitization goes further. It cleans or transforms data to remove anything unsafe (like stripping HTML tags from a comment) instead of rejecting it.
Explain like I'm 10
Validation is a bouncer checking IDs at the door and turning away anyone who doesn't qualify. Sanitization is a coat check that removes anything dangerous from a bag before letting it in, instead of turning it away.
Examples
Manual validation before using data
app.post("/signup", (req, res) => {
const { email, age } = req.body;
if (typeof email !== "string" || !email.includes("@")) {
return res.status(400).json({ error: "Invalid email" });
}
if (typeof age !== "number" || age < 13) {
return res.status(400).json({ error: "Invalid age" });
}
createUser({ email, age });
res.status(201).json({ ok: true });
});The route won't create a user until it has confirmed the data looks right.
Using a validation library for a declarative schema
const { z } = require("zod");
const signupSchema = z.object({
email: z.string().email(),
age: z.number().min(13),
});
app.post("/signup", (req, res) => {
const result = signupSchema.safeParse(req.body);
if (!result.success) {
return res.status(400).json({ error: result.error.issues });
}
createUser(result.data);
res.status(201).json({ ok: true });
});Instead of hand-writing every check, you declare the expected shape once as a schema, and the library validates the data against it in one call.
How it works
Validation usually runs early, often as middleware before the route's main logic. It checks the body, query string, or route parameters against rules: is the field present, is it the right type, is it within an allowed range or set of values?
If the data fails, the request is rejected right away with a clear error, before any database call or business logic. Sanitization also runs early, but it transforms the data (trimming whitespace, escaping special characters, removing disallowed HTML) instead of rejecting it.
Why does it exist?
Trusting incoming data blindly causes two kinds of problems:
- Ordinary bugs, like a function crashing because a number field was actually text.
- Security holes, like an attacker sending crafted data to manipulate a database query or inject a script other users will see.
Validation and sanitization catch both at the door, before bad data can do damage deeper in the system.
When to use it
Validate and sanitize any data from outside your trusted backend code: request bodies, query strings, route parameters, uploaded file names. This matters most before the data touches a database, is rendered into a page, or is used to build a file path.
When not to use it
Data your backend generated itself and never exposed to outside input doesn't need the same checks. Re-validating data you fully control adds overhead with no safety benefit.
Common mistakes
Validating only on the frontend and assuming the backend doesn't need to check again.
Checking only that a field exists, not its type or shape, so malformed data slips through.
Confusing validation (rejecting bad data) with sanitization (cleaning it up) and using only one when you need both.
Practice exercises
- Easy:
Write validation for a POST /login route that requires both
usernameandpasswordto be non-empty strings. - Medium:
Reject a
signuprequest if theagefield is present but not a positive number. - Hard:
Explain the difference between rejecting a comment that contains HTML tags (validation) and stripping the tags before saving it (sanitization). Describe a situation where each is the right choice.
Interview questions
What's the difference between validation and sanitization?
Validation checks data against expected rules and rejects it if it fails. Sanitization cleans or transforms data to remove unsafe parts instead of rejecting it.
Why can't you rely solely on frontend validation?
Anything can send a request, not just your frontend. A malicious or buggy client can skip frontend checks entirely, so the backend must validate on its own.
Why is validating data early in the request lifecycle useful?
It stops bad data before it reaches business logic or a database, preventing crashes and security issues instead of finding them deeper in the system.
What does a schema-based validation library (like zod or Joi) buy you over hand-written `if` checks?
You declare the expected shape once and get consistent parsing, type coercion, and error messages automatically. Hand-written checks get scattered across routes and drift out of sync.
What's the difference between a validation library that throws on failure and one that returns a result object, like zod's `safeParse`?
A throwing API means wrapping every call in try/catch. A result object like { success, data | error } lets you check .success without exceptions. That fits validation well, since invalid input is a common, expected outcome, not an exceptional one.
Why does type coercion, like converting a query-string "42" into the number 42, matter for validation?
Query strings and route parameters always arrive as strings, even when they represent numbers or booleans. A schema that wants a number must convert the value, not just check typeof, or every correct numeric query param would fail.
What's an object-injection risk validation should guard against beyond type checks, e.g. in a MongoDB query built from `req.body`?
A field like { password: { "$ne": null } } sent as JSON can be read as a MongoDB query operator instead of a literal value, which can bypass an equality check. Validating that the field is a plain string, not an object, before using it in a query closes this off.
What is HTML/script sanitization specifically protecting against?
Cross-site scripting (XSS). If user text containing <script> tags or event handlers is stored and later rendered into a page without sanitizing or escaping, that script runs in other users' browsers as if it were part of the trusted site.
What's the difference between escaping and stripping when sanitizing user input meant to be displayed as HTML?
Escaping converts special characters, like < to <, so they show as literal text instead of markup. The content looks the same. Stripping removes disallowed tags or characters, which changes the content.
Why doesn't `typeof age !== "number"` alone fully validate a numeric field?
It only rules out non-numeric types. NaN and Infinity are both of type "number" in JavaScript, so you also need a check like Number.isFinite(age) to get a usable number.
What's mass assignment, and how does validation help prevent it?
Passing all of req.body into a database create or update lets a client set fields it shouldn't control, like role: "admin". Validating against a schema that allows only specific fields, and ignores or rejects the rest, stops extra fields from getting through.
Why should validation happen before any database call, rather than letting the database reject bad data on its own?
A failing database constraint, like a NOT NULL violation, still wastes a round trip and often shows up as a vague database error. Validating first avoids the wasted work and gives the caller a clear, actionable message.
What does it mean to validate at the boundary of a system?
Checking data as it enters the system, e.g. when a request arrives. Everything past that point (business logic, database calls) can then assume the data has the right shape, without re-checking it everywhere.
Why might you sanitize a filename before using it to write a file to disk?
Path traversal. A filename like ../../etc/passwd can escape the upload directory if used directly. Sanitize it (remove path separators, resolve to a safe base directory) before building a real file path.
What's the risk of trusting a simple email-format check, like a string containing `@`, as proof an email address is real and reachable?
It only shows the format looks plausible, not that the address exists or belongs to the person. Proving a real, owned address needs a step like sending a verification email.
How should a validation error response differ from a plain 500, in terms of what it tells the caller?
It should say which field failed and why, e.g. "email must be a valid email address", because the caller can fix the request. A 500 means a server-side problem the caller can't do anything about.
Why is it important to validate the contents of array and object fields, not just that the field itself is an array or object?
Being 'an array' says nothing about what's inside. An endpoint expecting numeric ids could get strings, objects, or a huge number of items. The schema must check each element, not just the outer shape.
What's a practical reason to enforce limits, like max string length or max array size, during validation beyond checking type and shape?
Without limits, a request with the right types and shape could still send an enormous string or array to burn memory or CPU, a form of denial-of-service. Validation should also cap the size of what it accepts.