TExcelTAD
Home › Node.js › Middleware

Node.js Middleware

Middleware is a function that sits between an incoming request and the code that finally answers it. Each middleware gets a chance to inspect the request, change it, answer it early, or pass it on to the next function in the chain. Logging, authentication, body parsing, CORS headers and error handling are all usually written as middleware.

Express made the pattern famous, but the idea is tiny. In this lesson you will build a middleware chain from scratch in plain Node, so you know exactly what a framework does for you.

The shape of a middleware

In Express-style frameworks a middleware has this signature:

js
function middleware(req, res, next) {
  // 1. look at or modify req / res
  // 2. either answer the request (res.end(...))
  //    or call next() to hand over to the next middleware
}
Action Effect
call next() continue with the next function in the chain
call next(err) skip to the error-handling middleware
send a response stop the chain — later functions never run
do nothing the request hangs until it times out (a common bug!)

Building a chain by hand

The heart of every middleware system is a small run function that calls the functions one after another. Here it is with fake request/response objects, so you can watch the order of execution:

node · try it yourself
function compose(middlewares) {
  return function handle(req, res) {
    let index = 0;
    function next(err) {
      const fn = middlewares[index++];
      if (!fn) return;
      if (err) return next(err);   // skip normal middleware while an error is pending
      fn(req, res, next);
    }
    next();
  };
}

const logger = (req, res, next) => {
  console.log(`-> ${req.method} ${req.url}`);
  next();
};

const addUser = (req, res, next) => {
  req.user = { name: 'ada' };
  next();
};

const hello = (req, res) => {
  res.end(`Hello, ${req.user.name}!`);
};

const app = compose([logger, addUser, hello]);

const fakeRes = { end: (body) => console.log('<- ' + body) };
app({ method: 'GET', url: '/' }, fakeRes);
-> GET /
<- Hello, ada!

Notice how addUser attaches data to req, and a later function reads it. That is how authentication middleware typically passes the logged-in user to route handlers.

Middleware in a real HTTP server

The same compose works with Node's http module, because req and res there are real objects. This example adds a logger, a timing-free "powered by" header, and a simple API-key check. The server listens on port 0 (a free port chosen by the OS), sends itself two requests and then closes.

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

function compose(stack) {
  return (req, res) => {
    let i = 0;
    const next = () => {
      const fn = stack[i++];
      if (fn) fn(req, res, next);
    };
    next();
  };
}

const log = (req, res, next) => {
  console.log('server saw', req.method, req.url);
  next();
};

const poweredBy = (req, res, next) => {
  res.setHeader('X-Powered-By', 'ExcelTAD');
  next();
};

const requireKey = (req, res, next) => {
  if (req.headers['x-api-key'] !== 'secret') {
    res.statusCode = 401;
    return res.end('Unauthorized');
  }
  next();
};

const handler = (req, res) => res.end('Top secret data');

const server = http.createServer(compose([log, poweredBy, requireKey, handler]));

server.listen(0, async () => {
  const url = `http://localhost:${server.address().port}/data`;

  const r1 = await fetch(url);
  console.log(r1.status, r1.headers.get('x-powered-by'), await r1.text());

  const r2 = await fetch(url, { headers: { 'x-api-key': 'secret' } });
  console.log(r2.status, r2.headers.get('x-powered-by'), await r2.text());

  server.close();
});
server saw GET /data
401 ExcelTAD Unauthorized
server saw GET /data
200 ExcelTAD Top secret data

The order of the array is the order of execution. poweredBy runs before requireKey, so even the rejected response carries the header.

Tip: Put cheap, general middleware (logging, headers) first and expensive or specific middleware (database lookups, route handlers) last.

Error-handling middleware

Express recognises error handlers by their four parameters: (err, req, res, next). When any middleware calls next(err) (or throws, in Express 5 also from async functions), the framework skips ahead to the next error handler. Let's add that to our hand-made version:

node · try it yourself
function compose(stack) {
  return (req, res) => {
    let i = 0;
    const next = (err) => {
      const fn = stack[i++];
      if (!fn) return;
      const isErrorHandler = fn.length === 4;
      try {
        if (err && isErrorHandler) fn(err, req, res, next);
        else if (err) next(err);
        else if (!isErrorHandler) fn(req, res, next);
        else next();
      } catch (e) {
        next(e);
      }
    };
    next();
  };
}

const parseJson = (req, res, next) => {
  req.body = JSON.parse(req.raw);   // throws on bad input
  next();
};
const route = (req, res) => res.send(200, `Created ${req.body.name}`);
const onError = (err, req, res, next) => res.send(400, `Bad request: ${err.name}`);

const app = compose([parseJson, route, onError]);
const res = { send: (status, text) => console.log(status, text) };

app({ raw: '{"name":"Lamp"}' }, res);
app({ raw: '{name: Lamp}' }, res);
200 Created Lamp
400 Bad request: SyntaxError

The Express way

With Express (installed with npm install express) the same ideas look like this. Express can't be installed on this site, so this block is for reading only:

js
import express from 'express';

const app = express();

app.use(express.json());                     // built-in body-parsing middleware
app.use((req, res, next) => {                // custom logger
  console.log(req.method, req.url);
  next();
});

app.get('/admin', requireKey, (req, res) => { // middleware for one route only
  res.json({ ok: true });
});

app.use((err, req, res, next) => {           // error handler: 4 parameters, registered last
  res.status(500).json({ error: err.message });
});

app.listen(3000);
Express middleware Purpose
express.json() parse JSON request bodies into req.body
express.static('public') serve files from a folder
cors (package) add CORS headers
helmet (package) set security-related headers
morgan (package) request logging

Note: Middleware registered with app.use() runs for every request; middleware passed to app.get('/path', mw, handler) runs only for that route.

Test yourself

What should a middleware do if it does not send a response itself?

  1. Return true
  2. Call next()
  3. Throw an error
  4. Nothing — the framework continues automatically

How does Express recognise an error-handling middleware?

  1. Its name starts with error
  2. It is registered with app.error()
  3. It takes four parameters (err, req, res, next)
  4. It returns a rejected promise

In which order do middleware functions registered with app.use() run?

  1. Alphabetically
  2. In the order they were registered
  3. In reverse order
  4. In parallel