Explain it simply
Explain it simply
In lesson 23 you fetched the whole list of users. A profile page, though, needs just one user, so the client puts the id in the URL and asks for /api/users/2.
When you write the route as /api/users/:id, the :id part is a placeholder. For /api/users/2 Express puts "2" into req.params.id, and for /api/users/99 it puts "99". One route serves every user; your job is to check that id and find the matching user.
There are three possible endings: the user is found, the id looks fine but nobody has it, or the id is not even a valid number. Each ending gets its own status code.
Problem → Why → Solution
The problem: looking up an id without checking it
The handler below has two bugs. First, it compares req.params.id (the string "2") with u.id (the number 2) using ===, which is never true, so even existing users are not found. Second, there is no return after res.status(404).json(...), so the code keeps running and tries to send a second response.
The client still receives the 404, but the server log fills with "Cannot set headers after they are sent to the client". In production, noise like this buries the errors that matter.
app.get('/api/users/:id', (req, res) => {
const user = users.find((u) => u.id === req.params.id); // "2" === 2 is false
if (!user) {
res.status(404).json({ error: 'User not found' }); // no return
}
res.json({ data: user }); // second response!
});Why it happens
A URL is just text, so every route parameter arrives as a string. And res.json() only sends the response; it does not stop your function. Stopping the function is the job of return, which you have to write yourself.
Core concept: read, convert, check, find
Every item route runs four steps in order. If a step fails, the route returns at once with the right status and never reaches the steps after it.
1. Read from req.params
The name after the colon in the route path becomes the key in req.params; /api/users/:userId would give req.params.userId. The value is always a string.
2. Convert with Number()
Number("2") is 2, Number("abc") is NaN and Number("1.5") is 1.5. parseInt("2abc") returns 2 and silently ignores the junk after it, which makes it a poor choice for checking ids.
3. Check the format, answer 400
If Number.isInteger(id) && id >= 1 is false, the client sent an id in the wrong format. Whether such a user exists is not even the question yet, so this is 400 Bad Request.
4. Find, then answer 404 or 200
users.find() returns the first matching item or undefined. undefined means the id was well formed but no such user exists, so 404. Otherwise the route sends 200 with { data: user }.
| Request | Status | Meaning |
|---|---|---|
| /api/users/2 | 200 | Found, here it is |
| /api/users/99 | 404 | Valid id, but no such user |
| /api/users/abc | 400 | The id itself is malformed |
Keeping 400 and 404 apart lets the client tell a bug it can fix (code that builds broken links) from a normal event (the user was deleted).
Route order: put static paths before :id
:id matches a whole segment but never crosses a /, so /api/users/2/orders does not match this route. /api/users/me does match, though, with id set to "me". If you add a route such as /api/users/me, register it above /api/users/:id, because Express checks routes in the order they were written.
- Read req.params.id (a string)
- Convert it with Number()
- Bad format: return 400
- Missing: return 404, else 200
Whenever a gate sends a response, leave the function with return: one request, exactly one response.
General pattern
app.get('/api/items/:id', (req, res) => {
const id = Number(req.params.id);
if (!isValid(id)) return res.status(400).json({ error: 'bad id' });
const item = items.find((it) => it.id === id);
if (!item) return res.status(404).json({ error: 'not found' });
res.json({ data: item });
});Pair every error response with return, so each request produces exactly one response.
Returning one user after checking the id
Keeping the same three users, this adds GET /api/users/:id. The response shapes are the { data } and { error } agreed in lesson 22. The test sends four ids: one that exists, one that does not, a word and a decimal.
const express = require('express');
const app = express();
app.use(express.json());
const users = [
{ id: 1, name: 'Aung Aung', role: 'admin' },
{ id: 2, name: 'Mya Mya', role: 'member' },
{ id: 3, name: 'Zaw Zaw', role: 'member' },
];
app.get('/api/users/:id', (req, res) => {
const id = Number(req.params.id); // params are always strings
if (!Number.isInteger(id) || id < 1) {
return res.status(400).json({ error: 'id must be a positive whole number' });
}
const user = users.find((u) => u.id === id);
if (!user) {
return res.status(404).json({ error: `User ${id} not found` });
}
res.json({ data: user });
});
app.use((req, res) => {
res.status(404).json({ error: `Cannot ${req.method} ${req.path}` });
});
const server = app.listen(0, async () => {
const base = `http://localhost:${server.address().port}`;
for (const id of ['2', '99', 'abc', '1.5']) {
const res = await fetch(`${base}/api/users/${id}`);
const body = JSON.stringify(await res.json());
console.log(`GET /api/users/${id} -> ${res.status} ${body}`);
}
server.close();
});Code breakdown
- Route parameter
app.get('/api/users/:id', (req, res) => {:id matches the whole URL segment in that position and lands in req.params.id.
- String to number
const id = Number(req.params.id); // params are always stringsTurning "2" into 2 makes the === comparison with the numeric ids in users work.
- Format gate
if (!Number.isInteger(id) || id < 1) {"abc" (NaN) and "1.5" stop here with 400; see the last two lines of the output.
- Existence gate
const user = users.find((u) => u.id === id);99 is well formed but not present, so find() returns undefined and the route answers 404.
- Early return
return res.status(404).json({ error: `User ${id} not found` });return leaves the handler right after sending, so res.json({ data: user }) below is never reached.
GET /api/users/2 -> 200 {"data":{"id":2,"name":"Mya Mya","role":"member"}}
GET /api/users/99 -> 404 {"error":"User 99 not found"}
GET /api/users/abc -> 400 {"error":"id must be a positive whole number"}
GET /api/users/1.5 -> 400 {"error":"id must be a positive whole number"}Express 5 no longer takes regex inside route paths
Older Express 4 tutorials show routes like /api/users/:id(\d+), where the (\d+) after the parameter means "digits only". Express 5 uses a newer path-to-regexp library that removed this syntax, so such a route throws an error as soon as it is registered.
In Express 5 you therefore check the id format inside the handler or a middleware. For a stricter check, test the raw string with a regex such as /^[1-9][0-9]*$/. That also guards against surprises in Number(), such as Number("0x10") being 16. The mini challenge uses this approach.
In real projects
In real projects
Every detail page (a product page, an order detail, a profile) calls an item route. With a database, users.find() turns into a query like SELECT ... WHERE id = $1, but the 400/404/200 decisions stay exactly the same.
The most important security rule is that finding an item is not enough to return it. If a logged-in user can change the id in the URL from 2 to 3 and see someone else's order, that is an IDOR (Insecure Direct Object Reference) vulnerability. After finding an item, also check whether this user may see it. Some APIs answer 404 when access is denied, so outsiders cannot even learn that the item exists.
Common mistakes
Common mistakes
Comparing a string id with === against a number id
u.id === req.params.id compares "2" with 2 and is always false. Nothing throws; every user just returns 404, so it looks like the data has vanished. Switching to == is not the fix; convert once with Number().
Forgetting return after an error response
Without return the handler keeps going and calls res.json() again. Node throws ERR_HTTP_HEADERS_SENT and Express 5 passes it to the error handler. You will not see it in the response, but it shows up in the logs.
Answering a malformed id with 404
Answering /api/users/abc with 404 makes the client think the user was deleted, and the bug in its link-building code is never found. A malformed id deserves 400.
Best practices
Best practices
- Convert the id once at the top of the handler and use only the number afterwards
- Include the requested id in the 404 message ("User 99 not found"); it helps a lot when reading logs
- Once more than two item routes need it, move the id check and lookup into a middleware
- Never put internal details such as database errors or stack traces in the error message
Mini challenge
Share a loadUser middleware across two routes
Move the id check and the lookup into a route-level middleware, loadUser(req, res, next). Use it on two routes, GET /api/users/:id and GET /api/users/:id/greeting; the greeting route returns { data: { message: 'Hello, <name>!' } }.
- Check the id with the regex /^[1-9][0-9]*$/ and answer 400 if it fails
- If the user is missing, answer 404 and do not call next()
- If found, store it in res.locals.user and call next()
- /0x10 would be 16 with Number(), but here it must answer 400
const express = require('express');
const app = express();
const users = [/* TODO: the same three users */];
function loadUser(req, res, next) {
// TODO: 400 unless req.params.id matches /^[1-9][0-9]*$/
// TODO: find the user; 404 if missing
// TODO: res.locals.user = user; then next()
}
// TODO: GET /api/users/:id -> { data: user }
// TODO: GET /api/users/:id/greeting -> { data: { message: 'Hello, Name!' } }
// TODO: listen on 0; request /3, /3/greeting, /7/greeting, /0x10; closeExpected: /3 answers 200 with Zaw Zaw's data, /3/greeting answers 200 with "Hello, Zaw Zaw!", /7/greeting answers 404 and /0x10 answers 400.
Show hint
Put the middleware in the route itself: app.get(path, loadUser, handler). res.locals is an object that lives for one request only, which makes it the right place to pass data from middleware to handler.
Show solution
const express = require('express');
const app = express();
const users = [
{ id: 1, name: 'Aung Aung', role: 'admin' },
{ id: 2, name: 'Mya Mya', role: 'member' },
{ id: 3, name: 'Zaw Zaw', role: 'member' },
];
// Route-level middleware: answer 400/404 itself, or hand the user to the route
function loadUser(req, res, next) {
if (!/^[1-9][0-9]*$/.test(req.params.id)) {
return res.status(400).json({ error: 'id must be a positive whole number' });
}
const user = users.find((u) => u.id === Number(req.params.id));
if (!user) {
return res.status(404).json({ error: `User ${req.params.id} not found` });
}
res.locals.user = user;
next();
}
app.get('/api/users/:id', loadUser, (req, res) => {
res.json({ data: res.locals.user });
});
app.get('/api/users/:id/greeting', loadUser, (req, res) => {
res.json({ data: { message: `Hello, ${res.locals.user.name}!` } });
});
const server = app.listen(0, async () => {
const base = `http://localhost:${server.address().port}/api/users`;
for (const path of ['/3', '/3/greeting', '/7/greeting', '/0x10']) {
const res = await fetch(base + path);
console.log(path, res.status, JSON.stringify(await res.json()));
}
server.close();
});Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- The :id in /api/users/:id arrives in req.params.id as a string
- Convert with Number(); answer 400 for bad format, 404 for missing, 200 with { data } when found
- Put return after every error response: one request, one response
- Finding an item is not enough; check that the user may see it (IDOR)
Route parameters — Express.js