Middleware
A middleware is a function that runs before (or between) the handlers,
with the same signature plus a third argument: next.
function logger(req, res, next) {
console.log(req.method, req.url);
next(); // passes control to the next middleware/handler
}
- If it calls
next(), the request continues to the next step. - If it responds (
res.json(...),res.status(...)) and does not callnext(), it stops the chain right there. This is the pattern for authentication or validation:
function requireAuth(req, res, next) {
if (!req.headers.token) {
res.status(401).json({ error: "Unauthorized" });
return; // stops: does not call next()
}
next(); // there is a token: continue
}
The typical status codes here:
- 401 Unauthorized (authentication is missing).
- 400 Bad Request (malformed or missing data).