Node.js ยท Chapter 19 of 43

Middleware

Middleware functions in Express run between the request and the final response, with access to `req`, `res`, and a `next()` function to pass control onward.

Middleware is used for logging, authentication, parsing bodies, error handling, and more, applied globally or to specific routes.

Writing middleware

A middleware function has the signature `(req, res, next)`. Calling `next()` passes control to the next middleware or route handler.

Applying middleware

Use `app.use()` to apply middleware to all routes, or pass it as an extra argument to a specific route.

Example 1 (javascript)
function logger(req, res, next) {
  console.log(req.method, req.url);
  next();
}
app.use(logger);
Output
GET /
GET /about

This logs every incoming request before passing control onward.

Example 2 (javascript)
app.get('/admin', requireAuth, (req, res) => {
  res.send('Welcome admin');
});
Output
Welcome admin (only if requireAuth calls next())

Middleware can be scoped to a single route by adding it before the handler.

Key points

  • Middleware runs between request and response.
  • Signature is (req, res, next).
  • next() passes control to the next middleware/handler.
  • app.use() applies middleware globally; per-route middleware is scoped.
๐Ÿ’ก Note: Forgetting to call next() will leave a request hanging forever.

๐Ÿ“ Quick Quiz

1. What three parameters does middleware receive?

2. What happens if next() is never called?

3. Which method applies middleware to all routes?