What is middleware in Express, and how does the execution order work?
3 minintermediatenodejsexpressmiddlewarenextpipeline
Quick Answer
Middleware are functions with (req, res, next) that run in the order registered, forming a pipeline. Each can inspect/modify req/res, end the response, or call next() to pass control on. Order matters: body parsers, logging, and auth must be registered before the routes that rely on them.
Detailed Answer
Answer: Middleware is the core abstraction in Express — a function that runs during the request/response cycle.
Signature and flow:
function logger(req, res, next) {
console.log(`${req.method} ${req.url}`);
next(); // pass control to the next middleware/route
}
app.use(logger);
Each middleware can:
- run code / modify
reqorres(e.g., attachreq.user), - end the cycle by sending a response, or
- call
next()to continue, ornext(err)to jump to error handling.
Execution order = registration order:
app.use(express.json()); // 1. parse JSON body
app.use(requestLogger); // 2. log
app.use('/api', authenticate); // 3. auth for /api routes
app.get('/api/me', handler); // 4. route handler
app.use(errorHandler); // 5. error middleware (last)
If express.json() were registered after the route, req.body would be undefined in the handler — a classic ordering bug.
Types of middleware:
- Application-level —
app.use(fn). - Router-level — mounted on an
express.Router(). - Path-scoped —
app.use('/admin', fn)runs only for matching paths. - Built-in —
express.json(),express.static(). - Third-party —
helmet,cors,morgan. - Error-handling — four args
(err, req, res, next).
Key idea: it's a pipeline — control flows top to bottom until something sends a response or calls next(err).