APIs with Express · Chapter 26 of 29

Project: the middleware pipeline

By the end of this chapter you can put an API's middleware in an order where every piece sees every response it should. Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.

  • Part: Projects
  • 6 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

Tapri's partner API launches tonight, and Third Wave's developer has two bug reports. Their browser gets a CORS error, but only when their key is wrong, so they cannot see why. And Tapri's logs show no 429s, though they know they hit the rate limit.

Every piece is already written: request ids, a logger, security headers, CORS, a rate limit, API keys. Each one works on its own. They are in the wrong order, and nothing warns you about that: the app starts, the happy path works, and the failures only show up on the answers nobody tested.

What you build: 6 tasks

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

  1. Task 1

    requestId and accessLog: an id and a log line for every response

    Export requestId(), which returns a middleware. An incoming X-Request-Id of 1 to 64 characters, all letters, digits or dashes, is kept ('blue-tokai-77'). Otherwise ('x y; rm -rf', or no header) it makes one: 'req-1', 'req-2' and so on, counting only the ids it makes, from 1 for each requestId(). It puts the id on req.id, sends it in the X-Request-Id response header, and passes the request on.

    Export accessLog(log), which returns a middleware that calls log once per request, after the response has been sent, with '<id> <METHOD> <URL as sent, query included> <status>': 'req-2 GET /api/menu?page=2 200', 'req-4 GET /kitchen 404'.

    In createApp({ log }), mount both so that every response, a 404 included, gets an id and a log line.

  2. Task 2

    notFound and errorHandler: the two ends of the pipeline

    Export notFound(req, res), which answers 404 with { error: 'Not found', requestId: req.id }, and errorHandler(err, req, res, next), which answers 500 with { error: 'Internal error', requestId: req.id } and never the error's own message.

    Mount them in createApp so a route that does not exist (POST /api/orders with a good key) gets { error: 'Not found', requestId: 'req-1' }, and a route that throws (loadMenu rejecting with 'menu-db.internal:5432 refused') gets { error: 'Internal error', requestId: 'req-2' }, with no menu-db anywhere in the answer. Both still get their X-Request-Id and their log lines: 'req-1 POST /api/orders 404' and 'req-2 GET /api/menu 500'.

  3. Task 3

    securityHeaders: on every response, errors included

    Export securityHeaders(), which returns a middleware that sets X-Content-Type-Options: nosniff, X-Frame-Options: DENY, Referrer-Policy: no-referrer and Content-Security-Policy: default-src 'none', and removes X-Powered-By.

    Mount it in createApp so that every response has them: a 200 from /health, the 404 for /nope and the 500 from a crashing /api/menu, and later the 204 preflights, 401s and 429s too.

  4. Task 4

    cors: allowed origins, preflights and readable errors

    Export cors(origins), which returns a middleware. It always adds Origin to the Vary header. A request whose Origin is in origins gets Access-Control-Allow-Origin set to that origin; any other origin (https://evil.example) gets no such header.

    A preflight, an OPTIONS request with an Access-Control-Request-Method header, is answered right there with 204 and Access-Control-Allow-Methods: GET, POST, Access-Control-Allow-Headers: Content-Type, X-Api-Key and Access-Control-Max-Age: 600, plus the security headers from task 3.

    Mount it in createApp so errors carry the header too: GET /nope from https://app.tapri.in gets 404 with Access-Control-Allow-Origin: https://app.tapri.in.

  5. Task 5

    rateLimit: a 429 that is still logged and readable

    Export rateLimit({ limit, windowMs, now }), which returns a middleware: a fixed window per req.ip that starts at that client's first request, and a new window once now() minus its start is windowMs or more. Every response it sees gets X-RateLimit-Limit and X-RateLimit-Remaining (left after this request, never below 0). Over the limit it answers 429 with { error: 'Too many requests', requestId } and Retry-After, the seconds until the window ends, rounded up.

    With limit 3 and windowMs 60000: requests at 0, 0 and 20 s leave '2', '1', '0'; one at 35.5 s gets 429 with Retry-After '25'; at 60 s a new window starts with Remaining '2'.

    Mount it in createApp with the limit, windowMs and now given to createApp. The 429 has the security headers and Access-Control-Allow-Origin and is logged ('req-4 GET /api/menu 429'), and a preflight is still answered 204 over the limit, without being counted.

  6. Task 6 · interview question

    Interview: requireApiKey, after CORS and the rate limit

    Export requireApiKey(keys), which returns a middleware. keys maps each API key to a café name. An X-Api-Key that is one of keys' own keys puts the café name on req.cafe (/api/whoami answers { cafe: 'Blue Tokai' }); a missing or unknown key, 'toString' included, answers 401 with { error: 'Missing or unknown API key', requestId }.

    Mount it in createApp for /api only: /health needs no key. The 401 has the security headers and Access-Control-Allow-Origin and is logged, preflights to /api get 204 without a key, and every request counts towards the rate limit, /health and wrong keys included. With limit 3 the log reads 'req-1 GET /health 200', 'req-2 GET /api/whoami 401', 'req-3 OPTIONS /api/whoami 204', 'req-4 GET /api/whoami 401', 'req-5 GET /api/whoami 429'.

What you will learn

  • The order is the design: a request goes down the list until something answers, and nothing after that runs for it.
  • What each piece must see: logs, headers and CORS on every answer, errors included.
  • Guards after the helpers: why CORS and counting come before a key check.
  • The two ends: a 404 after every route, the error handler last.

More in Projects

Build "Project: the middleware pipeline" 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.