Loading video player…

Follow a Request Through Middleware

In this lesson, you followed requests down the assistant’s Express app, function by function, and moved a route that never answered to where it could.

Key Points

  • A route below the fallback never runs. A /health route added at the bottom of server.js, below the download’s 404 fallback, answers 404 with {"error":"Not found"}. The timer’s line still shows up in the server’s terminal, because the functions at the top ran.
  • Express sees the app as a list of functions, in the order the file registers them: requestId, timer, express.json(), express.static("public") (the file server, which sends the page’s files from public, and public/index.html for /), the /ask route with promptVersion("v2") before its handler, then the 404 fallback, which answers 404 Not found to any request that reaches it.
  • A request enters at the top. Each function either answers it or calls next() to hand it to the function below.
  • Express skips a route whose method or path doesn’t match. app.post("/ask", ...) only takes POST requests to /ask.
  • The fallback has no path, so it matches every request that gets that far, and it answers. Nothing below it sees the request.
  • Watch out: Express doesn’t gather all its middleware and run it before the routes. It runs everything in file order, so express.json() registered below /ask would come too late, and the route would find req.body undefined.
  • Moving the /health route above the fallback fixes it. The route then answers 200 with {"ok":true}, and the fallback still catches every address nothing above it answers.
  • A hiker’s question, POST /ask with a JSON body, runs six functions. First come requestId, timer, express.json(), which reads the question into req.body, and express.static(), which only serves files to GET and HEAD requests, so it passes the request on. Inside the /ask route, the middleware that promptVersion("v2") returns sets X-Prompt-Version: v2, and then the handler answers. The page, GET /, runs four: requestId, timer, express.json() (no body), and express.static(), which finds public/index.html and answers.
  • Express runs your functions from top to bottom, and the first one that answers ends the request. Functions every request needs go at the top, routes below them, and the fallback last.

Final Code

server.js, with the /health route above the fallback (the /ask route’s body is unchanged):

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

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

app.post("/ask", promptVersion("v2"), async (req, res) => {
  // ...
});
app.get("/health", (req, res) => res.json({ ok: true }));

app.use((req, res) => res.status(404).json({ error: "Not found" }));

app.listen(3000, () => console.log("Ridgeline Huts assistant on http://localhost:3000"));

Check it with curl in a second terminal while the server runs:

Language: Shell
$ curl -i http://localhost:3000/health
HTTP/1.1 200 OK
X-Powered-By: Express
X-Request-Id: 3e1839d9-4047-45dc-a3a9-2d72e30e744f
...

{"ok":true}

Next, in Log One JSON Line per Request, you’ll decide what’s worth writing down about each request.

00:00 In the last lesson, you registered an ID and a timer at the top of the server file. Now you’ll follow one request down the app’s functions, and see why that place matters.

00:11 Say Amara, the volunteer who looks after Ridgeline Huts’ server, asks for a health check: an address a monitor calls during the season, which tells it the server runs.

00:21 It can’t tell whether the answers are good. You add a short route for it at the bottom of the file, where new code usually goes. Restart the server, and request the health address with curl in a second terminal.

00:34 The answer is a 404, with the error Not found.

00:39 Yet the server’s terminal shows the timer’s line for this request, with its ID. So some of your functions ran, but the health route didn’t.

00:49 Express sees the app as a list of functions, in the order the file registers them. Your ID and timer come first. Then the JSON reader, and the file server, which sends the page’s files from the public folder.

01:01 For the site’s root address, that’s the index file. Then the ask route, with your prompt-version function before its handler. Last comes the download’s fallback.

01:10 It answers Not found to any request that reaches it. Your new route sits below it.

01:17 A request enters at the top. Each function either answers it, or calls next to hand it to the function below.

01:25 Follow the health request. The ID function adds the ID, and passes it on. The timer starts its clock, and passes it on. The JSON reader finds no body to read, so it passes the request on.

01:40 The file server finds no health file in the public folder, and passes it on too. The ask route only takes POST requests to that one path, so Express skips it.

01:52 Then the fallback. It has no path, so it answers every request that gets this far. The request ends there, and the health route below it never sees it. Watch out: Express doesn’t gather all its middleware and run it before the routes.

02:08 It runs everything in file order. A JSON reader registered below the ask route would come too late, and that route would find no body in the request.

02:18 To fix it, move the health route above the fallback. Your ID and timer stay at the top, where the last lesson put them. Restart, and request it again. This time, it answers 200, with ok set to true.

02:34 The fallback still catches every address that nothing above it answers. It does that job because it’s last.

02:43 Now count what runs for a hiker’s question: a POST request to the ask route, with a JSON body. The ID and the timer run. The JSON reader reads the question into the request’s body.

02:56 The file server only serves files to GET and HEAD requests, so it passes this one on. The ask route matches. Its prompt-version function adds its header, and passes it on.

03:09 Then the handler answers. That’s six functions, and the health route and the fallback never run. Now the browser asks for the page itself, a GET request for the site’s root address.

03:22 Your turn: pause the video and predict how many of these functions run for it.

03:32 Four. The ID, the timer, and the JSON reader, which finds no body. Then the file server answers with the index file. Nothing below it runs.

03:44 Express runs your functions from top to bottom, and the first one that answers ends the request.

03:51 So functions that every request needs, like your ID and timer, go at the top. Routes go below them. The fallback goes last. Every request passes through your timer, which prints a line of plain text.

04:04 In the next lesson, Log One JSON Line per Request, you’ll decide what’s worth writing down about each request.

Become a Member to join the conversation.