Write Your First Middleware

In the last lesson, you sent the wall’s API a V14, a problem set next year, and a name made of spaces, and it stored all three. You also found where the fix belongs: at the boundary, before a request reaches any route. Express has one mechanism for running code there, called middleware.

Before you write middleware that checks anything, you’ll see how it works with two jobs that don’t depend on what the client sends. In this lesson, you’ll write two functions that run for every request to the wall’s API: one assigns an ID, and the other times the request. By the end, you’ll know the shape every middleware function in this course shares. That shape starts with how a function gets a turn at every request.

Give Every Request an ID

Ines has a problem that has nothing to do with bad data. When Arjun’s front desk page shows an error, she writes down the time and what she clicked, and you go looking through the terminal for the matching request. With a few members using the page at once, that’s guesswork. A request ID, a unique string the server attaches to each request and sends back in a response header, turns it into a lookup.

A route handler can’t do this job alone, because you’d have to repeat the same lines in every route. Instead, you write one middleware function, which Express calls for each request before the route. Create a file called middleware.ts next to app.ts:

Language: TypeScript Filename: middleware.ts
import type { NextFunction, Request, Response } from "express";

export function addRequestId(
  req: Request,
  res: Response,
  next: NextFunction,
) {
  const id = crypto.randomUUID();
  res.locals.requestId = id;
  res.set("X-Request-Id", id);
  next();
}

The first two parameters are the req and res your route handlers already receive. Line by line, here’s what addRequestId() does with them:

  • crypto.randomUUID() makes a random ID. It’s the same call store.ts uses for a new problem’s id.
  • res.locals is an object Express creates fresh for each request, for passing values from middleware to whatever runs later for that request. Express types it loosely. Any name is allowed, and TypeScript treats its value as any, so it accepts requestId without an extra declaration. It also won’t catch a typo like res.locals.requestID.
  • res.set() sets a response header. The header goes out with whatever response the route sends later.

The third parameter, next, is new. It’s a function Express passes in, and calling it says “I’m done, hand this request to the next function in line.” Watch out: middleware that neither sends a response nor calls next() leaves the request hanging, and the client waits.

The function does nothing until Express knows about it. app.use() registers middleware for every request, in the order you call it. Open app.ts and add the import and the first app.use() line:

Language: TypeScript Filename: app.ts
import express from "express";
import { addRequestId } from "./middleware.ts";
import { problemsRouter } from "./routes/problems.ts";
import { logRouter } from "./routes/log.ts";

export const app = express();

app.use(addRequestId);
app.use(express.json());
app.use("/problems", problemsRouter);
app.use("/log", logRouter);

You pass addRequestId itself, without parentheses, because Express calls it later, once per request. Save both files, and npm run dev restarts the API. In your second terminal, ask for The Slab:

Language: Shell
$ curl -i http://localhost:3000/problems/2
HTTP/1.1 200 OK
X-Powered-By: Express
X-Request-Id: c665353a-e671-4883-85f8-b0c8f12cc7ce
Content-Type: application/json; charset=utf-8
Content-Length: 94
ETag: W/"5e-EvvZ+ttB4fLspfjE3P38hJOB1k8"
Date: Fri, 27 Nov 2026 10:24:21 GMT
Connection: keep-alive
Keep-Alive: timeout=5

{"id":"2","name":"The Slab","colour":"blue","grade":"V2",
"setOn":"2026-09-05","retired":false}

The body is wrapped here for display. The route didn’t change, yet the response now has an X-Request-Id header. Your ID will differ, and so will the next one, because the middleware runs again for every request.

Now see the warning about next() for yourself. Comment out the next(); line in addRequestId(), save, and send the same request. The --max-time 5 option makes curl give up after five seconds instead of waiting for as long as you let it:

Language: Shell
$ curl -i --max-time 5 http://localhost:3000/problems/2
curl: (28) Operation timed out after 5002 milliseconds with 0 bytes received

Nothing came back, not even a status line. The middleware set a header and returned, and Express had no way of knowing it should carry on, so the route never ran. Put next(); back and save. Every middleware function must either end the response or call next(). If you’re curious about the opposite slip, ask:

Time Every Request

The ID is only half of Ines’s lookup. When she reports an ID, you need a line in the terminal that carries the same ID, plus what the request was and how it went. While you’re writing that line, it can also say how long the request took, which tells you whether the front desk page is slow because of the API or something else.

Timing needs a start and an end. The start is straightforward. The middleware runs before the route, so it can note the time and then call next(). The end is harder, because a function later in line can finish its work after next() has already returned. For a POST, express.json() is still reading the request body at that moment, so the route hasn’t even started.

If you log the status right after next(), a POST shows 200, whether the route later answers 201 or refuses it with 422. The file write in a successful POST only adds to the wait.

The response tells you when it’s done instead. Node’s response object emits a "finish" event once the whole response has been handed over to be sent, and res.on() registers a function to run then. Add a second middleware function to middleware.ts:

Language: TypeScript Filename: middleware.ts
export function timeRequest(
  req: Request,
  res: Response,
  next: NextFunction,
) {
  const start = performance.now();
  res.on("finish", () => {
    const ms = (performance.now() - start).toFixed(1);
    console.log(
      `${res.locals.requestId} ${req.method} ${req.originalUrl}`,
      `${res.statusCode} ${ms} ms`,
    );
  });
  next();
}

performance.now() returns a time in milliseconds, with fractions, so the difference between two calls is how much time passed between them. The arrow function passed to res.on() runs later, after the route has answered, so res.statusCode holds the status that was really sent. req.originalUrl is the full path with its query string, even inside a router.

Notice that timeRequest() still calls next() straight away. It only registers the function for later, so it never holds up the request.

To see the two middleware functions work together, register timeRequest() in app.ts right after addRequestId(), and update the import to bring in both:

Language: TypeScript Filename: app.ts
import { addRequestId, timeRequest } from "./middleware.ts";
// ...
app.use(addRequestId);
app.use(timeRequest);
app.use(express.json());

Save and send four requests: fetch a problem that exists, fetch one that doesn’t, fetch a filtered list, and try to add a new problem with no name, which the route refuses:

Language: Shell
$ curl -i http://localhost:3000/problems/2
$ curl -i http://localhost:3000/problems/99
$ curl -i "http://localhost:3000/problems?grade=V2"
$ curl -i -H "Content-Type: application/json" \
  -d '{"colour":"yellow","grade":"V1","setOn":"2026-11-26"}' \
  http://localhost:3000/problems

Each response carries its own X-Request-Id header. In the terminal running the API, each request gets one line:

Language: Shell
Crux Corner API on http://localhost:3000
c665353a-e671-4883-85f8-b0c8f12cc7ce GET /problems/2 200 5.6 ms
fd7617dc-af22-41e6-80d6-115b725dd291 GET /problems/99 404 1.1 ms
9c4e5d5f-c9ab-4337-b15c-bbb0262d6fd0 GET /problems?grade=V2 200 0.6 ms
1421e316-f64c-41d3-b587-a942db31cc1c POST /problems 422 7.1 ms

Your IDs and times will differ. The failed requests are logged too, with the 404 and 422 they really got, because "finish" fires for every completed response, whatever its status. A request the client abandons before the response is finished may leave no line at all, which is fine for now. The time covers only the server’s side, not the trip across the network or the work the front desk page does afterward.

Now when Ines reads an ID off the page, you search the terminal for it and find the request, its status, and its time. If you’d like more practice, try this:

Spot the Middleware You Already Had

The starting project’s app.ts already had an app.use() line before you touched it: app.use(express.json()). That’s middleware too, and it’s the reason your routes can read req.body at all.

You can see its shape in Node’s REPL, an interactive JavaScript shell. Open one in the project folder with node. A REPL can’t use an import statement, so load Express with import(), which returns a promise you can await:

Language: Shell
$ node
Welcome to Node.js v26.13.1.
Type ".help" for more information.
> const { default: express } = await import("express");
undefined
> const parseJson = express.json();
undefined
> parseJson
[Function: jsonParser]
> parseJson.length
3

Press Ctrl+D to leave the REPL. For a function with ordinary parameters like these, .length is how many parameters it declares, and jsonParser declares three, as addRequestId() and timeRequest() do. For a JSON request, it reads the body, parses it, puts the result on req.body, and calls next(). It follows the same contract as your two functions, doing one job and then passing the request on.

That also explains the parentheses. express.json is a function that returns middleware, configured by the options you could pass in. Calling express.json() creates that middleware, the jsonParser you looked at in the REPL. You’ll write a function like that for validation later in this course. That’s all you need about it for now.

Before you move on, run npm run check to confirm there are no type errors.

Check that you can write and read middleware like this. For the first question, Sofia adds this to app.ts, before the routers, to see what arrives:

Language: TypeScript
app.use((req, res) => {
  console.log(req.method, req.path);
});

Answer these on paper:

  1. With Sofia’s function in place, what does curl -i http://localhost:3000/problems show, and what does the terminal show?
  2. Arjun wants every response from the wall’s API to carry the header X-Wall: Crux Corner. Write the middleware and the line that registers it.
  3. Mei suggests timing the request with a console.log() right after next() in timeRequest(), without res.on(). Why can that log the wrong status for POST /problems?
  4. In app.ts, why is it app.use(addRequestId) but app.use(express.json())?

Question 1: The terminal logs GET /problems, and curl shows nothing and waits. Sofia’s function never calls next() and never sends a response, so the request stops there. Adding next as a third parameter and calling it fixes it.

Question 2: One possible answer, in middleware.ts:

Language: TypeScript Filename: middleware.ts
export function addWallHeader(
  req: Request,
  res: Response,
  next: NextFunction,
) {
  res.set("X-Wall", "Crux Corner");
  next();
}

In app.ts, add addWallHeader to the named import from ./middleware.ts, then register it before the routers, so it runs before any route answers:

Language: TypeScript Filename: app.ts
import {
  addRequestId,
  addWallHeader,
  timeRequest,
} from "./middleware.ts";
// ...
app.use(addWallHeader);

Question 3: next() can return before the route has answered. For a POST, express.json() is still reading the body when next() returns, so the route hasn’t run yet and res.statusCode is still the default 200, not the 201 or 422 the route sends later. The "finish" event fires only once the response has gone out.

Question 4: addRequestId is the middleware, so you pass the function for Express to call. express.json() is called once, and it returns the middleware that Express then calls for each request.

Every response from the wall’s API now carries an X-Request-Id header, and each completed request leaves a timing line in the terminal. You’ve seen that express.json() follows the same contract. In the next lesson, Follow a Request Through the Chain, you’ll watch one request travel through these functions in order and see which one answers.

Become a Member to join the conversation.