DevPath · Learn to code ESPTEN

Middleware in Express

Middleware and next

Middleware

A middleware is a function that runs before (or between) the handlers, with the same signature plus a third argument: next.

function logger(req, res, next) {
  console.log(req.method, req.url);
  next(); // passes control to the next middleware/handler
}
function requireAuth(req, res, next) {
  if (!req.headers.token) {
    res.status(401).json({ error: "Unauthorized" });
    return; // stops: does not call next()
  }
  next(); // there is a token: continue
}

The typical status codes here:

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 →
The middleware chain →