DevPath · Learn to code ESPTEN

Middleware in Express

The middleware chain

An ordered pipeline

In Express, middleware form a chain (a pipeline). The request goes through them in the order they are registered, and each link decides:

app.use(logger);        // 1st for ALL routes
app.use(requireAuth);   // 2nd
app.get("/tasks", listTasks); // final handler

If requireAuth responds with a 401, the handler listTasks never runs: the request is already resolved.

Global vs. per-route

Application-level middleware (logging)

A classic case is logging every request. The middleware usually enriches the req object (adds data to it) or notes something somewhere before passing the baton:

function logger(req, res, next) {
  req.timestamp = Date.now(); // enriches the request
  console.log(req.method, req.url);
  next(); // essential so the request doesn't hang!
}

Golden rule: a middleware that doesn't respond must call next(). If it forgets, the request stays hung forever.

Put this into practice

DevPath is a hands-on course: you read the theory here; in the app you put it into practice with exercises that really run, offline.

Start free in the app →
← Middleware and nextView the module →