In the last lesson, you watched requests walk the wall’s API. Express started at the top of one list and stopped at the first function that answered. That picture matters whenever you add a line to app.ts, because you have to decide where the line goes.
In this lesson, you’ll add two new middleware functions to the wall’s API and register each one where it applies: for every request, for one path, or for one route. You’ll also learn to read an app.ts file and predict which functions run for a request and which one answers. Start where most people add a new line, at the bottom of the file.
Add a Header at the Bottom of app.ts
Arjun is updating the front desk page while you change the API, and he wants the page to know which version of the API answered it. He asks for an X-Api-Version header on every response. It’s the same kind of job as addRequestId(), so add a third function to middleware.ts:
middleware.ts
export function addApiVersion(
req: Request,
res: Response,
next: NextFunction,
) {
res.set("X-Api-Version", "1");
next();
}
The function sets one header and passes the request on. In app.ts, add it to the import and register it. The bottom of the file is where you’d add a new route, so that’s where the new line goes:
app.ts
import express from "express";
import {
addApiVersion,
addRequestId,
timeRequest,
} from "./middleware.ts";
import { problemsRouter } from "./routes/problems.ts";
import { logRouter } from "./routes/log.ts";
export const app = express();
app.use(addRequestId);
app.use(timeRequest);
app.use(express.json());
app.use("/problems", problemsRouter);
app.use("/log", logRouter);
app.use(addApiVersion);
Save both files, and npm run dev restarts the API. Before you send a request, predict the answer: Does curl -i http://localhost:3000/problems/2 show an X-Api-Version header?
$ curl -i http://localhost:3000/problems/2
HTTP/1.1 200 OK
X-Powered-By: Express
X-Request-Id: 7959218d-bd22-4e67-bd36-f2b903207ca9
Content-Type: application/json; charset=utf-8
Content-Length: 94
ETag: W/"5e-EvvZ+ttB4fLspfjE3P38hJOB1k8"
Date: Fri, 27 Nov 2026 10:43:52 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. There’s an X-Request-Id header but no X-Api-Version.
Express doesn’t collect every app.use() line first and run them all before the routes. It walks the list in registration order.
This request passed addRequestId(), timeRequest(), and express.json(), entered the problems router, and its GET /:id route answered. That answer ended the walk, so the request never reached the last line.
You can confirm that addApiVersion() itself works. Ask for a path that no route handles:
$ curl -i http://localhost:3000/walls
HTTP/1.1 404 Not Found
X-Powered-By: Express
X-Request-Id: 7fcc87b9-5dec-4fea-bf90-c8dd67bad314
X-Api-Version: 1
Content-Security-Policy: default-src 'none'
X-Content-Type-Options: nosniff
Content-Type: text/html; charset=utf-8
Content-Length: 144
Date: Fri, 27 Nov 2026 10:43:52 GMT
Connection: keep-alive
Keep-Alive: timeout=5
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Cannot GET /walls</pre>
</body>
</html>
This time, the header is there. Nothing above the last line answered /walls, so the walk reached addApiVersion(). It set its header and called next(), and with nothing left in the list, Express sent its own 404 page. That page is HTML, while the API’s errors use its JSON error shape. You’ll replace the page later in the course. A line below the routes runs only for requests that no route answered.
The fix is to move the line up. Put app.use(addApiVersion); above the routers, after timeRequest():
app.ts
app.use(addRequestId);
app.use(timeRequest);
app.use(addApiVersion);
app.use(express.json());
app.use("/problems", problemsRouter);
app.use("/log", logRouter);
Save, and send the request for The Slab again. The response now carries X-Api-Version: 1 next to its X-Request-Id. From here on, read app.ts from top to bottom as the path every request travels.
Order also decides what each function sees, and the same rule explains it. Suppose express.json(), the middleware the project started with, ended up below the two routers:
app.ts
app.use(addApiVersion);
app.use("/problems", problemsRouter);
app.use("/log", logRouter);
app.use(express.json());
Here’s how that version of the API responds to the request from the last lesson, the new problem with no name:
$ curl -i -H "Content-Type: application/json" \
-d '{"colour":"yellow","grade":"V1","setOn":"2026-11-26"}' \
http://localhost:3000/problems
HTTP/1.1 400 Bad Request
X-Powered-By: Express
X-Request-Id: 260d4038-8001-402e-b53e-459b9cc54787
X-Api-Version: 1
Content-Type: application/json; charset=utf-8
Content-Length: 98
ETag: W/"62-y01axFKNzNjvMhxwHPasMH7v7gc"
Date: Fri, 27 Nov 2026 10:44:02 GMT
Connection: keep-alive
Keep-Alive: timeout=5
{"error":{"code":"empty_body","message":"Send a JSON object
in the request body.","details":null}}
The request had a body, but the route says it didn’t. The API blames Ines for its own mistake, and nothing in the terminal tells you so. Last time, the same request got a 422.
When the POST route ran, express.json() was still further down the list, so nothing had parsed the body yet. As a result, req.body was undefined, and readJsonBody() answered 400. The body above is wrapped for display. Keep express.json() above every route that reads req.body.
If you’d like to test the rule on the two functions from the last lesson, ask:
Register Middleware for One Path or One Route
Not all middleware belongs on every request. Ines’s new problems will soon get a check. Before you write one, you’ll want to see what the front desk page really sends. Add one more function to middleware.ts that logs the request body, labeled with the request’s ID:
middleware.ts
export function showBody(
req: Request,
res: Response,
next: NextFunction,
) {
console.log(res.locals.requestId, "body:", req.body);
next();
}
showBody() only gives you a temporary look at what arrives. You’d remove a log of whole request bodies before real use, because bodies can carry personal data, such as the members’ first names in the climbing log.
You only care about requests for problems, so register showBody() for that path. When app.use() gets a path before the function, the function runs only for requests whose path starts with it. Add showBody to the import in app.ts. Then add the new line above the problems router, so the walk reaches it before the router answers:
app.ts
app.use(express.json());
app.use("/problems", showBody);
app.use("/problems", problemsRouter);
app.use("/log", logRouter);
Save, and send four requests: the filtered list, The Slab, the problem with no name, and the climbing log:
$ curl -i "http://localhost:3000/problems?grade=V2"
$ curl -i http://localhost:3000/problems/2
$ curl -i -H "Content-Type: application/json" \
-d '{"colour":"yellow","grade":"V1","setOn":"2026-11-26"}' \
http://localhost:3000/problems
$ curl -i http://localhost:3000/log
The terminal running the API shows this:
4d0022f1-0a3e-4421-9ef1-30351b586690 body: undefined
4d0022f1-0a3e-4421-9ef1-30351b586690 GET /problems?grade=V2 200 5.7 ms
246b8624-253d-44a5-8f14-4279615f6f8d body: undefined
246b8624-253d-44a5-8f14-4279615f6f8d GET /problems/2 200 1.1 ms
329e1277-cab4-42c9-9939-1b99ef4bcf89 body: { colour: 'yellow', grade: 'V1', setOn: '2026-11-26' }
329e1277-cab4-42c9-9939-1b99ef4bcf89 POST /problems 422 8.2 ms
16737790-500a-44c6-8c2c-1d6ce1326907 GET /log 200 0.6 ms
Every request under /problems got a body line, with or without a query string or an ID after the path. GET /log didn’t, because its path doesn’t start with /problems. The prefix counts whole path segments, so a path like /problemset doesn’t match either. Each body line also comes before its timing line, because showBody() runs on the way down the list, and the timing line waits for the response to finish.
The GET lines are noise, though. These GET requests send no body, so req.body is undefined. The only body you want to see is the one Ines’s page sends to POST /problems. For that, list the middleware in the route itself, before its handler, as requireJson() was in the last lesson. Delete the app.use("/problems", showBody); line and showBody from the import in app.ts. Then, in routes/problems.ts, import showBody and add it to the POST route:
routes/problems.ts
import express from "express";
import { showBody } from "../middleware.ts";
// ...
problemsRouter.post("/", showBody, async (req, res) => {
// ...
});
Express runs the functions a route lists from left to right, and each middleware function passes the request on with next(). Send the first and third requests from above again, the filtered list and the problem with no name:
e25ea878-4184-459e-a43b-6300c78f66ba GET /problems?grade=V2 200 0.9 ms
9696232b-96a7-45a3-9cec-6d9ffe492960 body: { colour: 'yellow', grade: 'V1', setOn: '2026-11-26' }
9696232b-96a7-45a3-9cec-6d9ffe492960 POST /problems 422 8.3 ms
Your IDs and times will differ. Only the POST logs its body now. You’ve used all three places to register middleware:
app.use(fn)runsfnfor every request that reaches that line.app.use("/problems", fn)runs it only for paths under/problems.- A route’s list,
problemsRouter.post("/", fn, handler), runs it only for that route, right before the handler.
In all three, the line still has to come before whatever answers the request. When you’re not sure which place fits a new function, ask:
Read app.ts From the Top
So far, you’ve checked each order by editing a file, saving, and sending a request. That works, but it’s slow when you want to compare many orders.
The widget below holds five of the seven registrations in app.ts from before you moved showBody() into the POST route: express.json(), the request ID, the timer, showBody() on the /problems path, and the problems router. Put them in any order you like with the arrows. Pick a request—the problem with no name, The Slab, or /walls—and send it.
The widget highlights each function that runs, in order, and shows what the route found in req.body and res.locals. Try a few orders and watch how the walk changes. Then try to make the route see no body or no request ID:
Whatever order you tried, the walk followed the same rule. It started at the top, skipped entries whose path didn’t match, and ran each function in turn until one answered. Anything below that answer never ran for that request, and the route could only read what the functions above it had already set.
Check that you can apply the rule without the widget. Tunde rearranged app.ts on his own copy of the wall’s API, and two things broke. Use his file for the first task:
app.ts
app.use(addRequestId);
app.use("/problems", problemsRouter);
app.use(express.json());
app.use("/log", logRouter);
app.use(addApiVersion);
- Arjun reports that responses to
GET /loghave noX-Api-Versionheader. Walk the request through Tunde’s file to find the cause, and say how to fix it. - Sofia wants
showBody()to log the body when Ines retires a problem withPATCH /problems/:id, and only then. Write the route’s first line. - In the wall’s API, Mei moved
app.use("/problems", showBody);belowapp.use("/problems", problemsRouter);, andGET /problems/2no longer logs a body line. Explain why, and name a request under/problemsthat still makes it log one.
Question 1: addRequestId() runs first. The problems router is skipped because /log doesn’t start with /problems. Then express.json() runs, and the log router’s GET / route answers with the climbing log. That answer ends the walk, so addApiVersion(), on the last line, never runs. Move app.use(addApiVersion); above the routers.
Question 2: List showBody in the PATCH route, before its handler:
routes/problems.ts
problemsRouter.patch("/:id", showBody, async (req, res) => {
Question 3: The router’s GET /:id route answers GET /problems/2, and that ends the walk before the moved line. showBody() runs only for requests under /problems that the router doesn’t answer, such as GET /problems/2/climbs. It logs body: undefined, and then Express sends its own 404 page.
Every response from the wall’s API now carries X-Api-Version, and showBody() logs only the bodies sent to POST /problems. That log line shows the body arriving, but showBody() lets anything through, including a V14 with a name. What should a check in that spot look for, and what should it answer? You’ll get to that soon.
First, in the next exercise, Stamp Requests at the Shoe Desk, you’ll give the front desk’s shoe rental shelf its own request IDs and timing, with each middleware registered where it applies.
It’s the course’s first coding exercise, and you’ll write the code in your browser instead of in your editor and terminal. Click Run Tests to check your code. The automated tests tell you what passed, and a failing test’s message points at what to change before your next try, so run them early and often. If the editor feels cramped, Full screen gives you more room.