Show contents
Chapter 5 of 7 · 20 min
Validate and protect
By the end of this chapter, you'll be able to
- Validate a request's body: presence, type, length
- Return clear errors with the right 4xx code
- Protect a route with an access token
- Tell 401 (not authenticated) from 403 (not authorised)
Never trust the client
A well-written mobile app sends correct data. But anyone can send an HTTP request to your server, without going through the app, with a tool like curl. The golden rule: everything that comes from the client is checked on the server. A check in the mobile app improves the user's comfort, but it protects nothing.
Validation happens in three steps:
- read the body and check that it is JSON (otherwise
400 Bad Request); - check each field: present, of the right type, of a reasonable length (otherwise
422 Unprocessable Content, with the list of problems); - only then, process the request.
function readJson(text) {
try {
return { ok: true, data: JSON.parse(text) };
} catch {
return { ok: false, response: { status: 400, body: { error: "the body is not valid JSON" } } };
}
}
function validateBook(data) {
const errors = [];
if (typeof data !== "object" || data === null || Array.isArray(data)) return ["the body must be a JSON object"];
if (typeof data.title !== "string" || data.title.trim() === "") errors.push("title: required text");
else if (data.title.length > 200) errors.push("title: 200 characters at most");
if (data.author !== undefined && typeof data.author !== "string") errors.push("author: must be text");
return errors;
}
for (const body of ['{"title":"Maïmouna","author":"Abdoulaye Sadji"}', '{"author":42}', "title=Maïmouna"]) {
const parsed = readJson(body);
if (!parsed.ok) { console.log(parsed.response.status, parsed.response.body.error); continue; }
const errors = validateBook(parsed.data);
console.log(errors.length ? 422 : 201, errors);
}
201 []
422 ["title: required text","author: must be text"]
400 the body is not valid JSON
Return all the errors at once: the client fixes everything in one go, instead of discovering the problems one by one.
All barriers are passed: only now do we touch the data.
Text description of the animation
- Without a valid token, the server does not know who is speaking: 401 Unauthorized.
- The token is valid, but this member is not allowed to delete: 403 Forbidden.
- The body is not JSON: 400 Bad Request.
- The JSON is readable but the fields are invalid: 422 with the list of errors.
- All barriers are passed: only now do we touch the data.
Protecting a route with a token
To know who sends a request, the client attaches an access token: a long secret string, obtained when signing in, sent in the Authorization header:
DELETE /api/books/4 HTTP/1.1
Authorization: Bearer 8f2c7e1d9a4b6f30c5e8a1d27b9f4c6e
The server finds who this token belongs to and what their rights are. Two codes not to confuse:
- 401 Unauthorized: the server does not know who you are (no token, unknown or expired token). The client must sign in;
- 403 Forbidden: the server knows who you are, but you are not allowed to do this.
const tokens = {
"8f2c7e1d9a4b6f30c5e8a1d27b9f4c6e": { name: "Awa", role: "board" },
"1d27b9f4c6e8f2c7e1d9a4b6f30c5e8a": { name: "Kofi", role: "member" },
};
function identify(headers) {
const [type, token] = (headers.authorization ?? "").split(" ");
return type === "Bearer" ? tokens[token] ?? null : null;
}
function deleteBook(headers, id) {
const user = identify(headers);
if (!user) return { status: 401, body: { error: "sign-in required" } };
if (user.role !== "board") return { status: 403, body: { error: "board only" } };
return { status: 204, body: null };
}
console.log(deleteBook({}, 4).status);
console.log(deleteBook({ authorization: "Bearer 1d27b9f4c6e8f2c7e1d9a4b6f30c5e8a" }, 4).status);
console.log(deleteBook({ authorization: "Bearer 8f2c7e1d9a4b6f30c5e8a1d27b9f4c6e" }, 4).status);
401
403
204
In Node.js, header names in req.headers are always lowercase: you read req.headers.authorization. In production, tokens are drawn at random with crypto.randomBytes(32).toString("hex"), have a limited lifetime and only travel over HTTPS.
Other essential protections
- Limit the body size: refuse beyond, say, 100 KB (
413 Content Too Large), so a client cannot saturate memory. - Rate limit: a few dozen requests per minute and per address on sensitive routes, such as sign-in (
429 Too Many Requests). - Never return internal details: on a
500error, a generic message for the client, and the details in the server's logs. - Never write a secret in the code: keys and passwords go into environment variables (
process.env).
Mini-lab: validate a registrationJavaScript
Output
Click “Run” to execute your code.Your code runs in your browser, isolated from the page. · Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor
Your turn
Worked exercise
Worked exercise: a complete POST route
Write createBook(headers, bodyText) that chains all the barriers: token (401), JSON (400), fields (422), then creation (201). Only known users can create a book, whatever their role.
Hint 1
identify, readJson and validateBook: the function only calls them in the right order.Hint 2
return as soon as it fails: the rest of the code is never reached.Show the solution and common mistakes
const tokens = { abc123: { name: "Awa", role: "member" } };
const books = [];
const identify = (h) => {
const [type, token] = (h.authorization ?? "").split(" ");
return type === "Bearer" ? tokens[token] ?? null : null;
};
const readJson = (t) => { try { return JSON.parse(t); } catch { return undefined; } };
const validateBook = (d) => {
if (typeof d !== "object" || d === null || Array.isArray(d)) return ["the body must be a JSON object"];
return typeof d.title === "string" && d.title.trim() ? [] : ["title: required text"];
};
function createBook(headers, bodyText) {
const user = identify(headers);
if (!user) return { status: 401, body: { error: "sign-in required" } };
const data = readJson(bodyText);
if (data === undefined) return { status: 400, body: { error: "invalid JSON" } };
const errors = validateBook(data);
if (errors.length) return { status: 422, body: { errors } };
const book = { id: books.length + 1, title: data.title.trim(), addedBy: user.name };
books.push(book);
return { status: 201, body: book };
}
const awa = { authorization: "Bearer abc123" };
console.log(createBook({}, '{"title":"Maïmouna"}').status);
console.log(createBook(awa, "Maïmouna").status);
console.log(createBook(awa, '{"title":" "}').body);
console.log(createBook(awa, '{"title":" Maïmouna "}').body);
401
400
{"errors":["title: required text"]}
{"id":1,"title":"Maïmouna","addedBy":"Awa"}
The title is saved without the surrounding spaces, thanks to trim(). In this simplified version, books.length + 1 is enough because no book is ever deleted.
Common mistakes:
- Validating the fields before checking the token: a stranger then learns how your API validates data.
- Using
JSON.parse(text) || …: a valid body such as0orfalsewould be mistaken for an error. Compare explicitly withundefined.
Summary
- 1Everything that comes from the client is checked on the server, even if the app already checks it.
- 2An unreadable body is a 400; invalid fields are a 422, with the list of all errors.
- 3A token in the Authorization header identifies the user.
- 4401: unknown identity; 403: known identity but forbidden action.
- 5Body size and request rate are limited too, and internal details are never revealed.
Your progress is saved on this device. Create a free account to keep your progress on all your devices.