Node.js Developer interview question · Most asked
How does middleware work in Express?
Summary
Middleware are functions (req, res, next) executed in registration order; each can modify req/res, end the response, or call next() to pass control. Error-handling middleware has four arguments (err, req, res, next) and is registered last.
Longer Answer
Typical stack: security headers (helmet), CORS, body parsing (express.json()), logging, auth, routes, 404 handler, error handler. Express 5 (stable since 2024) forwards rejected promises from async handlers to the error handler automatically; in Express 4 you needed wrappers.
Code Example
import express from "express";
import helmet from "helmet";
const app = express();
app.use(helmet());
app.use(express.json({ limit: "1mb" }));
app.get("/users/:id", async (req, res) => {
const user = await users.find(req.params.id); // Express 5 forwards rejections
if (!user) return res.status(404).json({ error: "Not found" });
res.json(user);
});
app.use((err, req, res, next) => {
req.log?.error(err);
res.status(err.status ?? 500).json({ error: err.expose ? err.message : "Internal error" });
});
Key Points
(req, res, next)chain in order- Error middleware has 4 params
- Order matters: parsers before routes
- Express 5 handles async errors
Deep dive: Request Lifecycle course: Express: The Middleware Stack and Error Handling
More most-asked Node.js Developer questions
- Why is CPU-bound work a problem in Node.js and how do you handle it?
- What are streams in Node.js and what is backpressure?
- What is the difference between `process.nextTick`, Promise microtasks, `setImmediate` and `setTimeout(fn, 0)`?
- Explain the phases of the Node.js event loop.
- What is Node.js and why is it well suited to I/O-heavy servers?
- How has asynchronous code evolved in Node.js: callbacks, Promises and async/await?
- Walk through how an Express app handles a request, including errors from async handlers.
- What are the differences between CommonJS and ES modules in Node.js?