Add a Request ID and a Timer

The overview left the Ridgeline Huts assistant on the eve of its first summer season. Evals, or evaluation tests, judged it on your laptop, but once hikers use it for real, you’ll hear “the answer took forever” or “it sent me the wrong way,” and you’ll need to find that one request among hundreds and see what it did.

This course builds that record, and every lesson ends with a number you produced. Here, you’ll give every request its own ID and measure how long it takes, with two short functions for Express, a Node.js web framework. First, get the assistant running.

Start the Assistant

In every lesson in this course, you’ll observe the same app. The code download below the overview video contains it. It’s the assistant and eval set from Evals You Can Trust, with the Express app, the page, the streamed answers, and the hut availability tool from Building AI Features restored. You don’t need to have taken those courses to follow along.

You need Node.js and an API key for OpenAI or Anthropic. The examples use Node.js 26. The project’s README.md has the details. In short, open a terminal in the starting-project folder and run npm install. Copy .env.example to .env and fill in your provider and key. Then start the server:

Language: Shell
$ npm start

> [email protected] start
> node --env-file=.env server.js

Ridgeline Huts assistant on http://localhost:3000

Open http://localhost:3000 and ask the page a question to check that answers stream back. Behind the page, server.js is an Express app, and app.post("/ask", ...) is the route that answers. It registers a function that Express calls for every POST request to /ask.

Besides text lessons, the course has short videos and in-browser coding exercises that use recorded data and need no key.

Give Every Request an ID

When hundreds of requests arrive, a hiker’s complaint or a log line needs to point at exactly one of them. A request ID is a unique label your app gives each request as it arrives. You could repeat that code in every route, but Express can do the job once for all of them.

Middleware is a function in Express’s request-response chain. Express calls it with the request, the response, and a function named next. You’ve used one already, since express.json() reads a request’s body before /ask sees it. Create a new file, middleware.js, next to server.js, with a middleware function of your own:

Language: JavaScript Filename: middleware.js
export function requestId(req, res, next) {
  const id = crypto.randomUUID();
  res.locals.requestId = id;
  res.set("X-Request-Id", id);
  next();
}

crypto.randomUUID() returns a random universally unique identifier (UUID) as a 36-character string. The crypto object is global in Node.js, so there’s nothing to import.

res.locals is an object Express creates for each request, where one function can leave data for the functions that run after it. Storing the ID there lets the timer, and later the log and the trace of the request’s steps, read it. res.set() adds a response header, which a program calling the API or your browser’s developer tools can read.

The last line, next(), hands the request on to the next function. Without it, Express doesn’t move on by itself, and the page waits for an answer that never comes. Every middleware function either answers or calls next().

If next() still feels abstract, the button below opens a chat with the mentor, with the question already filled in, so you can trace it through your own code:

Time Each Request

A hiker’s “it took forever” means little until you know how long your server spent on that request. Timing it takes some care, because middleware runs when a request arrives, but a streamed answer finishes seconds later. So the timer notes the start time and leaves a callback for the response’s "finish" event, which Node.js emits once the whole response has been handed off for sending. Add the timer function to middleware.js:

Language: JavaScript Filename: middleware.js
export function timer(req, res, next) {
  const start = performance.now();
  res.on("finish", () => {
    const ms = Math.round(performance.now() - start);
    console.log(
      `${req.method} ${req.path} ${res.statusCode}`,
      `${ms} ms ${res.locals.requestId}`,
    );
  });
  next();
}

performance.now() returns a time in milliseconds, made for measuring durations. The timer calls next() straight away, so it holds nothing up. Only the callback waits, then logs the line with the ID that requestId() stored.

If a hiker closes the page mid-answer, Node.js emits "close" without "finish", so the timer logs completed responses only. That biases your numbers. People give up on the slow answers, so completed requests alone make the server look faster than hikers experienced.

The callback runs later than the rest of the middleware, so check with the mentor that you can say when:

Now register requestId and timer in server.js, at the top, before express.json(), the middleware that serves the page’s files, and the routes:

Language: JavaScript Filename: server.js
import express from "express";
import { requestId, timer } from "./middleware.js";

const app = express();
app.use(requestId);
app.use(timer);
app.use(express.json());
app.use(express.static("public"));
// ...

app.use() registers a middleware function for every request. Express calls functions in the order you register them, so timer() comes after requestId(), whose ID it logs. Both run before the routes below them. That’s all you need about order for now.

Set the Prompt Version on One Route

Some middleware belongs on one route only. Your traces will need the prompt version behind each answer, and only /ask uses a prompt. Rather than hard-code one version inside a middleware function, write a middleware factory: a function that takes a setting and returns a middleware function that uses it. Add it to middleware.js:

Language: JavaScript Filename: middleware.js
export function promptVersion(version) {
  return (req, res, next) => {
    res.set("X-Prompt-Version", version);
    next();
  };
}

Express needs a function it can call with req, res, and next on every request. promptVersion("v2") runs once, when you register it, and returns that function, which remembers version. Import promptVersion in server.js and list its returned middleware in the /ask route, between the path and the handler, so it runs there only:

Language: JavaScript Filename: server.js
app.post("/ask", promptVersion("v2"), async (req, res) => {
  // the handler's code, unchanged
});

The literal "v2" keeps the example short. A team would pass the version from wherever the assistant loads its prompt, so the label can’t drift from the prompt used to generate the answer.

To check the factory, restart the server with Ctrl+C and npm start. Then, in your browser:

  1. Open the developer tools and select the Network panel.
  2. Ask the page a question.
  3. Select the ask request in the list.
  4. Find X-Prompt-Version: v2 among its response headers.

Read Your First Number

Leave the server running. In a second terminal, ask for the page’s headers with curl:

Language: Windows PowerShell
PS> curl.exe -I http://localhost:3000/
HTTP/1.1 200 OK
X-Powered-By: Express
X-Request-Id: 0b6221ab-9820-47a7-8e55-708507b20cf3
...
Language: Shell
$ curl -I http://localhost:3000/
HTTP/1.1 200 OK
X-Powered-By: Express
X-Request-Id: 0b6221ab-9820-47a7-8e55-708507b20cf3
...

The X-Request-Id header carries the ID, and the server’s terminal shows the same ID next to HEAD / 200 5 ms. Your IDs and times will differ.

Now ask the page another question. When the answer finishes streaming, a line like this one appears in the server’s terminal:

Language: Shell
POST /ask 200 1188 ms ac356251-f156-48bd-990f-894d9fab6e5f

That example run took 1,188 milliseconds on December 2, 2026, with OpenAI’s gpt-5.4-mini-2026-03-17, the answer model pinned in model/config.js.

The duration on your own POST /ask line is your first number. It’s the time your server takes from receiving a request to handing off the last word. Network delivery and the browser’s rendering come on top.

One number says little, because the next answer may take twice as long. So this course reports percentiles: the p95, for example, is the time within which 95 of every 100 requests finish. You’ll compute them later in the course.

For more answers, leave the server running and start the project’s traffic simulator in the second terminal. It sends last season’s recorded hiker questions to /ask over HTTP, as the page would. Unlike a hiker, it waits for each answer and never gives up, so real hikers’ response times vary more.

Language: Shell
$ npm run traffic -- --month=july

Each simulated request produces a log line and uses tokens from your provider, so press Ctrl+C in the traffic simulator’s terminal when you’ve seen enough.

Check Your Understanding

Try these before you reveal the answers:

  1. Say you write a middleware function that sets res.locals.started and returns without calling next(). What happens when someone asks the page a question?
  2. Why does timer() compute the duration inside the "finish" callback instead of right after it calls next()?
  3. The wardens want to try prompt v3 on a new /ask-beta route while /ask keeps v2. Write the registration for /ask-beta, and say why promptVersion takes parentheses there while timer doesn’t.
  1. The request stops in your middleware. No route runs, and the page waits. Call next() at the end.
  2. Right after next(), the route has only started, and a streamed answer takes seconds more. The "finish" event fires once the server has handed off the whole response, so the duration covers all of it.
  3. List the factory’s result in the route:

    Language: JavaScript
    app.post("/ask-beta", promptVersion("v3"), handler);
    

    timer is already a middleware function, so you hand Express the function itself. promptVersion is a factory, and calling it with "v3" returns the middleware, so one factory serves both versions.

Every request now carries an ID, and every completed one a duration. In the next lesson, Follow a Request Through Middleware, you’ll watch a request travel down this chain of functions and see why each function’s registration order matters.

Become a Member to join the conversation.