Skip to content
Tutorials Center
My learning

Topics

Lesson 4 of 43 ยท Getting Started

Inside Express: Building a Mini Express

See how Express works inside by reading a 60-line mini framework: a layer stack, path matching, next(), error handlers and the res helpers used in every lesson.

This course cannot install Express in your browser, so every runnable example uses a small stand-in framework that we write ourselves. This lesson takes that stand-in apart. Once you see that an Express app is only an ordered list of functions plus some matching rules, routing and middleware stop feeling magical.

The stand-in is not Express. It is about 60 lines, it skips many features, and its path matching is simpler. What it shares with Express is the shape: app.use, app.get, req.params, res.json, next() and four-argument error handlers.

The big idea: a stack of layers

When you call app.get('/users', handler) or app.use(logger), Express does not run anything. It pushes a layer onto a list. A layer is a small record: which method it applies to, which path, and which function to call.

flowchart LR
  A["Incoming request"] --> B["Layer 1<br/>use(logger)"]
  B -->|"next()"| C["Layer 2<br/>get /users"]
  C -->|"no match"| D["Layer 3<br/>get /users/:id"]
  D -->|"no match"| E["404 fallback"]

The request visits layers in the order they were registered. A layer that does not match is skipped; a matching layer either responds or calls next().

For every incoming request the app walks that list from the top. If a layer matches, its function runs. The function either sends a response (the walk ends) or calls next() (the walk continues). If the list runs out, the app sends a 404.

One request, step by step

Parse Fill req.path and req.query.
Match Find the next layer for this method and path.
Run Call the handler with req, res, next.
Finish A response ends it. Otherwise next() moves on.

Running out of layers means a 404.

1 / 2

Piece 1: registering layers

JavaScript
const layers = [];
const add = (method, path, fns) => {
  for (const fn of fns.flat()) layers.push({ method, path, fn });
};

app.use = (...fns) => add(null, null, fns);
app.all = (path, ...fns) => add(null, path, fns);
for (const verb of ['get', 'post', 'put', 'patch', 'delete']) {
  app[verb] = (path, ...fns) => add(verb.toUpperCase(), path, fns);
}

use has no method and no path, so it matches everything. app.get and friends store an upper-case method. app.all has a path but no method, so it matches every method. Passing several functions (app.get('/x', a, b)) adds several layers. Real Express does the same thing with more bookkeeping.

Piece 2: matching a layer

JavaScript
const match = (layer, req) => {
  if (layer.method && layer.method !== req.method) return null;
  if (!layer.path) return {};
  const keys = [];
  const source = layer.path.replace(/:(\w+)/g, (_, key) => (keys.push(key), '([^/]+)'));
  const found = new RegExp(`^${source}/?$`).exec(req.path);
  if (!found) return null;
  return Object.fromEntries(keys.map((key, i) => [key, decodeURIComponent(found[i + 1])]));
};

The function returns null for "no match" or an object of parameters for "match". A path like /users/:id becomes the regular expression ^/users/([^/]+)/?$, and the captured text becomes req.params.id. Real Express uses a library called path-to-regexp with a richer syntax; Route Parameters shows more of it.

Piece 3: the request handler and next()

The app itself is a function (req, res), which is exactly what http.createServer expects.

JavaScript
let i = 0;
const next = (err) => {
  const layer = layers[i++];
  if (!layer) {
    if (err) return res.status(500).json({ error: err.message });
    return res.status(404).send(`Cannot ${req.method} ${req.path}`);
  }
  const params = match(layer, req);
  const isErrorHandler = layer.fn.length === 4;
  if (!params || isErrorHandler !== Boolean(err)) return next(err);
  req.params = params;
  try {
    if (isErrorHandler) layer.fn(err, req, res, next);
    else layer.fn(req, res, next);
  } catch (e) {
    next(e);
  }
};
next();

Read it slowly, because this is the heart of Express:

  • i is the position in the list, private to this one request.
  • next() takes the following layer. If it does not match, it calls itself again to try the one after.
  • If an error is being passed along (next(err)), normal layers are skipped and only error handlers run. Express recognizes them by their four parameters (fn.length === 4), and the stand-in uses the same trick.
  • A throw inside a handler is caught and turned into next(e).
  • Past the last layer: 500 for an error, 404 otherwise.

Piece 4: response helpers

JavaScript
res.status = (code) => ((res.statusCode = code), res);
res.json = (data) => {
  res.setHeader('content-type', 'application/json; charset=utf-8');
  res.end(JSON.stringify(data));
};
res.send = (text) => {
  res.setHeader('content-type', 'text/plain; charset=utf-8');
  res.end(String(text));
};

res.status returns res, which is why res.status(404).json(...) chains. These are the same names real Express offers, though real Express handles many more value types in send.

Run the whole thing

The full stand-in is included below between the marker comments, followed by an app that uses layers, parameters, middleware and an error handler. Read the output lines in order.

Node.js The complete mini Express in action

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

You should see the logging layer run for all three requests, the parameter and query values filled in for /users/7, the thrown error turned into JSON by the error handler, and a 404 for the unknown path.

Stopping at the first response

A layer that sends a response should usually not call next() as well. In the next example the first route replies, so the second one for the same path never runs. This is why route order matters.

Node.js First matching response wins

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

What the stand-in simplifies

It is worth knowing the gap, so you do not trust the stand-in where real Express differs:

  • Real Express supports app.use('/prefix', ...) and mounted routers; the stand-in's use matches everything.
  • Real res.send picks the content type from the value (string, buffer, object) and adds an ETag.
  • Real Express parses query strings with the settings you choose and exposes many req helpers.
  • Real error handling sends an HTML page in development and a plain page in production, and it logs.

When a lesson depends on one of these, it says so.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does calling app.get('/users', handler) do in Express?

    Registering a route only stores it. The handler runs later, when a request matches.
  2. 2. How does Express tell an error handler from a normal handler?

    A function with (err, req, res, next) has length 4, so Express treats it as an error handler.
  3. 3. Two routes match GET /same. The first calls res.send and does not call next(). What happens?

    Layers run in order, and the walk stops when a response is sent without next().
  4. 4. What happens when no layer matches and no error is pending?

    The end of the layer list is reached, and the fallback sends a 404.

Summary

  • An Express app is an ordered list of layers; each request walks the list.
  • A layer has a method, a path and a function; use layers match everything.
  • next() moves to the next matching layer; sending a response ends the walk.
  • Error handlers have four parameters and only run when an error is passed.
  • The stand-in is a faithful shape of Express but far smaller; real code stays read-only here.

Next: Project Setup and Structure.