Intermediate Node.js Interview QuestionsIntermediateConcept
Node.js · Question 42
What is middleware in Node.js HTTP servers?
Direct answer
Middleware is a chain of functions (req, res, next) that inspect or transform requests before the final handler — auth, logging, body parsing, CORS; each calls next() to continue or ends the response to stop the chain.
Raw http.createServer has no middleware — frameworks compose ordered functions. Fastify uses hooks and plugins with similar pipeline semantics and encapsulation.
Why interviewers ask
- Order matters — body parser before route that reads req.body; auth before protected routes.
- next(err) — skip to error-handling middleware in Express-style stacks.
- Short-circuit — send 401 and return without next() for failed auth.
- Cross-cutting concerns — logging, rate limits, request IDs — not duplicated per route.
middleware-chain.mjs
function logger(req, res, next) {
console.log(req.method, req.url);
next();
}
function requireJson(req, res, next) {
if (!req.headers["content-type"]?.includes("application/json")) {
res.writeHead(415).end("JSON only");
return;
}
next();
}
function compose(...fns) {
return (req, res) => {
let i = 0;
const next = () => {
const fn = fns[i++];
if (fn) fn(req, res, next);
};
next();
};
}