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.
function logger(req, res, next) {
console.log(req.method, req.url);
next();
}
app.use(logger);GET /
GET /aboutThis logs every incoming request before passing control onward.
app.get('/admin', requireAuth, (req, res) => {
res.send('Welcome admin');
});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.
