CPCODELAB
Express

What Is Middleware?

8 min read

What Is Middleware?

Middleware is a function with the signature (req, res, next) that sits between the HTTP request arriving and the route handler sending a response. Each middleware can read and modify req and res, then either end the cycle or call next() to pass control to the next middleware.

js
function logger(req, res, next) {
  console.log(`${req.method} ${req.path} — ${new Date().toISOString()}`);
  next(); // must call next, otherwise the request hangs
}

app.use(logger);

app.use() mounts middleware globally. You can also scope it to a path prefix: app.use("/api", middleware) only runs for routes that start with /api.

The Middleware Stack

Express processes middleware and route handlers in the order they are registered. Think of it as a pipeline: each function either passes the request downstream with next() or terminates it with a response.

If a middleware forgets to call next() and does not send a response, the client will hang until the connection times out. Always ensure every code path either calls next() or sends a response.

Ready to test yourself?
Practice Express— quiz & coding exercises