Middleware

Topic 3 of 4 in Express6 min readIntermediateFree course

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.

A request passes through helmet (security headers), express.json (parse body), a logger, requireAuth (check token) and finally the route handler which calls res.json. Each step calls next() to continue. If there is no token, requireAuth responds with 401 and the chain stops. Each middleware can change req and res and call next, end the response, or call next(err) to jump to the error handler.

Writing middleware

JavaScript
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:

  1. Call next() to pass the request along.
  2. Send a response (res.json(…), res.status(401)…), which ends the chain.
  3. 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:

JavaScript
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

JavaScript
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 route

Order matters

Middleware runs in registration order. Get it wrong and things silently fail:

JavaScript
app.post('/courses', createCourse); // ✗ req.body is undefined here…
app.use(express.json());            // …because the parser is registered after the route

A typical order for an API:

JavaScript
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 response

Configurable middleware

When middleware needs options, write a function that returns a middleware. Most library middleware works this way — express.json({ limit }), cors({ origin }), rateLimit({ … }):

JavaScript
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:

JavaScript
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:

JavaScript
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.

Exercise

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.

JavaScript
import express from 'express';
const app = express();

function responseTime(req, res, next) {}
function requireApiKey(req, res, next) {}

Summary

  • Middleware is a function (req, res, next) that runs as part of the request pipeline.
  • It can modify req/res, end the response, call next() to continue, or next(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.