APIs with Express · Chapter 6 of 29

Middleware

By the end of this chapter you can run code on every request before it reaches a route: number it, check who sent it, log its answer, or turn it away. Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.

  • Part: Middleware
  • 5 tasks
  • Express
  • In the all labs plan

The first 2 chapters of APIs with Express are free. This one comes with the all labs plan.

Why you need this

Three partner cafés start calling Tapri's API next week, and Kabir has a list. Every request gets a number, so support can find it in the logs. Callers without a partner API key are turned away. Every answer leaves a log line with its status. Ravi wants the stock route for his operations team only, and Meera wants a switch that closes the API in the 4 pm rush.

With what you know, every route would start with the same lines: read the key, check it, number the request, write the log. Twenty routes means twenty copies, and the one route where you forget them is open to anyone and missing from the logs.

What you build: 5 tasks

Each task has tests. You write the code in the lab's editor and press Check.

  1. Task 1

    requestId: a number for every request

    Export requestId, a function that returns a middleware. The middleware numbers the requests it sees 1, 2, 3 and so on. For each request it puts the number on req.id as a number, sends it back in the X-Request-Id header as text, and passes the request on.

    Each call of requestId() starts its own count at 1, so two apps never share a count.

  2. Task 2

    requireApiKey: only partner cafés get in

    Export requireApiKey(keys), which returns a middleware. keys maps each partner's API key to its café name. The middleware reads the x-api-key request header.

    With no header it answers 401 with { error: 'Missing API key' }. With a key that is not in keys it answers 403 with { error: 'Unknown API key' }. With a known key it puts the café name on req.cafe and passes the request on.

    A name that every object has, such as toString, is not a known key.

  3. Task 3

    createApp: a log line for every response

    In createApp, before the routes, register two middleware that every request goes through: your requestId() from task 1 (so the first response has X-Request-Id 1), and a logger.

    createApp takes an optional log function, createApp({ log }). Once each response has been sent, call log once with one line: the method, the URL as the client sent it (query string included) and the status code, separated by spaces. GET /menu?page=1 logs 'GET /menu?page=1 200', and GET /nope logs 'GET /nope 404'.

  4. Task 4

    GET /admin/stock: for the operations team only

    Add GET /admin/stock. It answers the stock object as JSON, but only when the x-role header is exactly ops. Without the header, or with any other role (rider, say), it answers 403 with { error: 'Operations only' }.

    Guard this route only: GET /menu stays open to a request with no headers at all.

  5. Task 5 · interview question

    Interview: maintenance, the switch that makes requests hang

    Fix maintenance(isOn). Its middleware asks isOn() on every request. While isOn() is true it answers 503 with { error: 'Back after the 4 pm rush' }. While isOn() is false, the request must go on to the next function: today it hangs, and the check gives up after 1.5 seconds.

What you will learn

  • Middleware: a function every request passes through on its way to the routes. It either answers, or hands the request on with next().
  • Guards: middleware that answers early (a 401, a 403) for the whole app or for one route.
  • The finish event: code that runs after the response has gone out, when its status is known.
  • The request that never ends: what happens when a middleware neither answers nor calls next().

More in Middleware

Build "Middleware" yourself

Partner cafés want Tapri’s menu online by Friday: you build its API. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.

The first 2 chapters of APIs with Express are free. This one comes with the all labs plan.