Middleware is a function that runs between the request arriving and the response being sent. It has access to req, res and next.
What middleware can do
- Run code (logging, timing)
- Change
reqorres(addreq.user) - End the request (send a 401)
- Call
next()to pass control to the next middleware or route
If middleware neither responds nor calls next(), the request hangs.
Where to use it
- For every request:
app.use(logger) - For a path:
app.use('/admin', requireAdmin) - For one route:
app.get('/profile', requireLogin, handler)
Popular middleware packages
cors (allow other domains), helmet (security headers), morgan (request logs), express-rate-limit, cookie-parser, multer (uploads).
Error-handling middleware
Has four arguments (err, req, res, next) and goes after all routes. Call next(err) anywhere to jump to it. (Express 5 also passes errors from rejected async handlers to it automatically.)
Example
import express from 'express';
const app = express();
// 1. Runs for every request
app.use((req, res, next) => {
const start = Date.now();
res.on('finish', () => console.log(`${req.method} ${req.url} ${res.statusCode} ${Date.now() - start}ms`));
next();
});
// 2. Route-level middleware
function requireApiKey(req, res, next) {
if (req.get('x-api-key') !== process.env.API_KEY) {
return res.status(401).json({ error: 'Invalid API key' });
}
next();
}
app.get('/api/secret', requireApiKey, (req, res) => res.json({ data: 'top secret' }));
app.get('/boom', (req, res, next) => next(new Error('Something broke')));
// 3. Error handler: four arguments, defined last
app.use((err, req, res, next) => {
console.error(err);
res.status(err.statusCode || 500).json({ error: 'Internal server error' });
});
app.listen(3000);
Every request is logged like "GET /api/secret 401 2ms". /api/secret needs the right x-api-key header. /boom is caught by the error handler, which returns a 500 JSON response.