Routing maps HTTP method + path to handlers. Middleware runs in order—logging, auth, body parsing—each calls next() or ends the response.
Express middleware chain
app.use((req, res, next) => {
console.log(req.method, req.url);
next();
});
app.use(express.json());
app.get('/api/health', (req, res) => {
res.json({ ok: true });
});
Order matters
Auth middleware before protected routes; error handler last with four args (err, req, res, next). Missing next() hangs requests.
Route parameters
app.get('/users/:id', (req, res) => {
res.json({ id: req.params.id });
});
Important interview questions and answers
- Q: What if middleware never calls next or res.end?
A: Client hangs until timeout—common bug when forgetting to return after sending response. - Q: app.use vs app.get?
A:usematches all methods/prefix paths;getmatches GET on exact route patterns.
Self-check
- What does next() do?
- Why put error middleware last?