TExcelTAD
Home › Express & NestJS › Express Middleware

Express Middleware

A middleware is a function with the signature (req, res, next). It can read or change the request, send a response, or call next() to hand control to the next function in line. Express is essentially a list of middleware; routes are just middleware with a method and path filter.

The three choices of a middleware

Every middleware must do exactly one of these:

Action Effect
send a response (res.json(...)) the chain stops here
call next() continue with the next matching middleware/route
call next(err) skip to the error-handling middleware

Watching the order

node · try it yourself
const express = require('express');

const app = express();
const trace = [];

app.use((req, res, next) => {
  trace.push('1. first middleware');
  next();
});

app.use((req, res, next) => {
  trace.push('2. second middleware');
  next();
});

app.get('/hello', (req, res) => {
  trace.push('3. route handler');
  res.json({ trace });
});

const server = app.listen(0, async () => {
  const res = await fetch(`http://localhost:${server.address().port}/hello`);
  console.log((await res.json()).trace.join('\n'));
  server.close();
});
1. first middleware
2. second middleware
3. route handler

Attaching data to the request

Middleware commonly decorates req (or res.locals) for later handlers. Here a request id and a start time are added; a header is set on the way out:

node · try it yourself
const express = require('express');

const app = express();
let counter = 0;

app.use((req, res, next) => {
  req.requestId = `req-${++counter}`;
  res.set('X-Request-Id', req.requestId);
  next();
});

app.get('/whoami', (req, res) => {
  res.json({ requestId: req.requestId });
});

const server = app.listen(0, async () => {
  const url = `http://localhost:${server.address().port}/whoami`;
  for (let i = 0; i < 2; i++) {
    const res = await fetch(url);
    console.log(res.headers.get('x-request-id'), await res.text());
  }
  server.close();
});
req-1 {"requestId":"req-1"}
req-2 {"requestId":"req-2"}

Scoping middleware

Registration Runs for
app.use(fn) every request
app.use('/admin', fn) every request whose path starts with /admin (any method)
app.get('/x', fn, handler) only GET /x — route-level middleware
router.use(fn) requests handled by that router

With app.use('/admin', fn), inside fn the mount path is stripped: req.path is /users for /admin/users, while req.baseUrl is /admin.

Running code after the response

next() returns before the response is finished, so to measure or log a completed request, listen for the response's finish event:

node · try it yourself
const express = require('express');

const app = express();
const log = [];

app.use((req, res, next) => {
  res.on('finish', () => log.push(`${req.method} ${req.originalUrl} -> ${res.statusCode}`));
  next();
});

app.get('/ok', (req, res) => res.json({ ok: true }));

const server = app.listen(0, async () => {
  const base = `http://localhost:${server.address().port}`;
  await fetch(base + '/ok');
  await fetch(base + '/missing');
  console.log(log.join('\n'));
  server.close();
});
GET /ok -> 200
GET /missing -> 404

Configurable middleware: factories

Real-world middleware is usually a function that returns a middleware, so it can take options. That's why you write express.json() with parentheses:

node · try it yourself
const express = require('express');

const app = express();

function requireHeader(name, expected) {
  return (req, res, next) => {
    if (req.get(name) !== expected) {
      return res.status(400).json({ error: `header ${name} must be "${expected}"` });
    }
    next();
  };
}

app.use('/v2', requireHeader('X-Api-Version', '2'));
app.get('/v2/status', (req, res) => res.json({ version: 2 }));

const server = app.listen(0, async () => {
  const url = `http://localhost:${server.address().port}/v2/status`;
  const bad = await fetch(url);
  const good = await fetch(url, { headers: { 'X-Api-Version': '2' } });
  console.log(bad.status, await bad.text());
  console.log(good.status, await good.text());
  server.close();
});
400 {"error":"header X-Api-Version must be \"2\""}
200 {"version":2}

Async middleware

In Express 5 a middleware may be async. If its promise rejects, Express calls next(err) for you. Still call next() explicitly on success:

js
app.use(async (req, res, next) => {
  req.user = await loadUserFromToken(req.get('authorization')); // throw → error handler
  next();
});

Tip: Popular third-party middleware: cors (CORS headers), helmet (security headers), morgan / pino-http (logging), express-rate-limit, multer (uploads), cookie-parser, express-session. Later lessons build simplified versions of several of these by hand so you understand what they do.

Test yourself

What happens if a middleware neither responds nor calls next()?

  1. Express responds with 200 automatically
  2. The request hangs until it times out
  3. Express skips to the next middleware
  4. The server crashes

Inside app.use('/admin', fn), what is req.path for a request to /admin/users?

  1. /admin/users
  2. /users
  3. /admin
  4. users

Why is express.json called with parentheses in app.use(express.json())?

  1. It's a class constructor
  2. It's a factory that returns the middleware, optionally configured
  3. Parentheses are optional
  4. It starts a JSON server