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 req or res (e.g., attach req.user),
  • end the cycle by sending a response, or
  • call next() to continue, or next(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-levelapp.use(fn).
  • Router-level — mounted on an express.Router().
  • Path-scopedapp.use('/admin', fn) runs only for matching paths.
  • Built-inexpress.json(), express.static().
  • Third-partyhelmet, 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).