Middleware
Overview
In Express, almost everything is middleware: parsing JSON bodies, serving static files, logging, checking login tokens, adding security headers, enforcing rate limits. Even your route handlers are a special kind of middleware.
A middleware is simply a function with the signature (req, res, next). For each request, Express passes the request through a chain of these functions in the order you registered them.
Writing middleware
function logger(req, res, next) {
console.log(`${new Date().toISOString()} ${req.method} ${req.originalUrl}`);
next(); // hand over to the next function in the chain
}
app.use(logger);Each middleware must do one of three things:
- Call
next()to pass the request along. - Send a response (
res.json(…),res.status(401)…), which ends the chain. - Call
next(err)(or throw, in Express 5) to skip to the error handler.
If it does none of these, the request hangs until the client gives up — a very common bug.
Adding information to req
Middleware often attaches data for later handlers. An authentication middleware, for example, works out who the user is and stores it on req:
async function requireAuth(req, res, next) {
const token = req.get('Authorization')?.replace(/^Bearer /, '');
if (!token) return res.status(401).json({ error: 'Login required' });
const user = await verifyToken(token); // throws if invalid → error handler
req.user = user;
next();
}
app.get('/me', requireAuth, (req, res) => {
res.json(req.user); // set by the middleware
});You can also use res.locals — an object that lives for the duration of one request — for values you want to share.
Where middleware applies
app.use(helmet()); // every request
app.use('/api', express.json()); // only paths starting with /api
coursesRouter.use(requireAuth); // every route in this router
app.delete('/courses/:id', requireAuth, requireAdmin, deleteCourse); // one routeOrder matters
Middleware runs in registration order. Get it wrong and things silently fail:
app.post('/courses', createCourse); // ✗ req.body is undefined here…
app.use(express.json()); // …because the parser is registered after the routeA typical order for an API:
app.use(helmet()); // 1. security headers
app.use(cors(corsOptions)); // 2. which websites may call the API
app.use(requestLogger); // 3. log every request
app.use(express.json({ limit: '100kb' })); // 4. parse bodies
app.use(rateLimiter); // 5. limit abuse
app.use('/api/v1', apiRouter); // 6. routes (with their own auth)
app.use(notFound); // 7. nothing matched → 404
app.use(errorHandler); // 8. errors → JSON responseConfigurable middleware
When middleware needs options, write a function that returns a middleware. Most library middleware works this way — express.json({ limit }), cors({ origin }), rateLimit({ … }):
function requireRole(...roles) {
return (req, res, next) => {
if (!roles.includes(req.user?.role)) {
return res.status(403).json({ error: 'You do not have permission to do that' });
}
next();
};
}
app.delete('/courses/:id', requireAuth, requireRole('admin', 'editor'), deleteCourse);Doing something after the response
Middleware runs before the handler, but you can react when the response finishes using the 'finish' event — the basis of request logging:
function requestLogger(req, res, next) {
const start = performance.now();
res.on('finish', () => {
const ms = (performance.now() - start).toFixed(1);
console.log(`${req.method} ${req.originalUrl} ${res.statusCode} ${ms}ms`);
});
next();
}Useful third-party middleware
| Package | What it does |
|---|---|
helmet |
sets security-related HTTP headers |
cors |
handles cross-origin requests from browsers |
express-rate-limit |
limits how many requests a client can make |
pino-http / morgan |
request logging |
compression |
gzip/brotli responses |
cookie-parser |
reads cookies into req.cookies |
multer |
handles file uploads |
You’ll use most of these later in the course.
Async middleware
Middleware can be async. In Express 5, a rejected promise is passed to the error handler just like a thrown error, so await freely:
app.use(async (req, res, next) => {
req.tenant = await loadTenant(req.hostname);
next();
});Keep middleware focused. Each one should do one job — log, authenticate, parse, limit. Small middleware is easy to reorder, test and reuse across routes and projects.
Timing and API-key middleware
Write two middleware functions. responseTime adds an X-Response-Time header with how many milliseconds the request took. requireApiKey returns 401 unless the x-api-key header matches process.env.API_KEY. Apply the first to every request and the second only to /admin routes.
import express from 'express';
const app = express();
function responseTime(req, res, next) {}
function requireApiKey(req, res, next) {}import express from 'express';
import { timingSafeEqual } from 'node:crypto';
const app = express();
function responseTime(req, res, next) {
const start = process.hrtime.bigint();
const originalWriteHead = res.writeHead;
res.writeHead = function (...args) {
const ms = Number(process.hrtime.bigint() - start) / 1e6;
res.setHeader('X-Response-Time', `${ms.toFixed(1)}ms`);
return originalWriteHead.apply(this, args);
};
next();
}
function requireApiKey(req, res, next) {
const given = Buffer.from(req.get('x-api-key') ?? '');
const expected = Buffer.from(process.env.API_KEY ?? '');
if (expected.length === 0 || given.length !== expected.length || !timingSafeEqual(given, expected)) {
return res.status(401).json({ error: 'Invalid API key' });
}
next();
}
app.use(responseTime);
app.use('/admin', requireApiKey);
app.get('/admin/stats', (req, res) => res.json({ users: 42 }));Summary
- Middleware is a function
(req, res, next)that runs as part of the request pipeline. - It can modify
req/res, end the response, callnext()to continue, ornext(err)to jump to error handling. - Order matters: middleware runs in the order it’s registered.
- Apply middleware globally (
app.use), to a path (app.use('/admin', …)), to a router, or to one route. - Configurable middleware is written as a factory function that returns the middleware.