# Add Request ID Logging to a Koa App

Yes. An agent adds a request-id middleware to your Koa app, puts the id on every response and log line including errors, tests it with supertest, and opens a PR.

[Run this on Rush](https://cloud.getrush.ai/run/add-request-id-logging/koa/). Opens the console with this prompt ready to send, in a Project that has your repository.

## What the agent does

The agent reads how requests are logged today before it adds an id to them. In a Koa project like koajs/examples, every example is a directory whose `app.js` exports `module.exports = new Koa()` and only calls `app.listen(3000)` when run directly (`if (!module.parent)`), which is what lets `blog/test.js` mount the app with `supertest.agent(app.listen())`. The root `package.json` pins `koa` at `^2.2.0`, `koa-logger` at `^3.0.0`, `@koa/router` at `^8.0.5` and `koa-body` at `^4.0.8`, with `mocha` `^5.0.0`, `supertest` `^3.0.0` and `should` for tests; the `test` script is `NODE_ENV=test mocha --harmony --reporter spec --require should */test.js`, `lint` is `eslint .` under `eslint-config-koa`, and `engines` says `node >= 7.6`. Three examples log: `blog/app.js` uses `koa-logger` as its first middleware, `compose/app.js` has a hand-written `logger` that prints `ctx.method`, `ctx.url` and the elapsed milliseconds unless `NODE_ENV` is `test`, and `errors/app.js` catches thrown errors, sets `ctx.status` from `err.status`, calls `ctx.app.emit('error', err, ctx)` and logs `err.message` in an `app.on('error')` handler. None of those lines carries anything that ties a log line to one request.

The agent writes the middleware as a new example, `request-id/app.js`, in the shape the repository uses, with a `request-id/test.js` beside it and a line in `Readme.md`. The middleware reads the incoming `X-Request-Id` header and keeps it only when it is short and made of letters, digits, dashes and underscores, so a proxy's id is preserved but a client cannot inject a log line; otherwise it makes one with `crypto.randomBytes(16).toString('hex')` rather than `crypto.randomUUID`, because the `engines` field still admits Node versions older than the one that introduced `randomUUID`. The id goes on `ctx.state.requestId` for the rest of the chain and on the response as `X-Request-Id`, so a caller can quote it when something goes wrong.

Errors need their own handling, and the agent explains why in the pull request. Koa's default error handler in `lib/context.js` unsets every response header before it writes its plain 500, then copies `err.headers` onto the response, so an id set on the context earlier would be gone from exactly the response a reader most wants it on. The middleware therefore catches, adds `X-Request-Id` to `err.headers`, and rethrows, which is the one path through which a header survives the default handler, and in `errors/app.js` the `app.on('error', (err, ctx) => …)` handler gains `ctx.state.requestId` on its log line, which is the line an operator greps for. For the request line, `koa-logger`'s transporter receives only the formatted string and an array of format, method, url, status, time and length, not the context, so in `blog/app.js` the agent builds the logger inside a small middleware that closes over `ctx.state.requestId` and prefixes it, and in `compose/app.js` it adds the id to the existing `console.log` format. No new dependency is added.

Tests use the repository's own pattern: `request-id/test.js` with `should` and `supertest` asserts that a response carries a hex `X-Request-Id`, that a request sent with `X-Request-Id: abc-123` gets `abc-123` back, that a header with spaces or over the length limit is replaced, and that the `errors` example's 500 still carries the header. The agent runs `npm test` and `npm run lint` in its sandbox and reads the output; `eslint-config-koa` is strict about unused variables and arrow callbacks, so the new files are written to pass it rather than adding `eslint-disable` lines.

## Start it with one API call

`POST https://api.phoenix.so/o/{org}/sessions`

```json
{
  "agent": "claude",
  "input": "Add request id logging to this Koa repository. Read package.json, Readme.md, .eslintrc.yml, blog/app.js, compose/app.js, errors/app.js and blog/test.js first. Add a request-id example directory with app.js and test.js in the same shape as the others: middleware that keeps a safe incoming X-Request-Id or generates one with crypto.randomBytes, stores it on ctx.state.requestId and sets it on the response, and on an error adds the header to err.headers before rethrowing, because Koa's default error handler strips response headers and then applies err.headers. Wire the id into the koa-logger line in blog/app.js, the hand-written logger in compose/app.js and the app.on('error') handler in errors/app.js. Add tests with supertest for a generated id, an echoed id, a rejected id and an error response. Do not add dependencies. Run npm test and npm run lint, include the output, list the example in Readme.md, and open a pull request.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
```

1. **Get an API key.** In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
2. **Send the request.** POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
3. **Read what came back.** Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

## What comes back

What comes back is a pull request that adds `request-id/app.js` and `request-id/test.js`, edits `blog/app.js`, `compose/app.js` and `errors/app.js`, and adds one line to the examples list in `Readme.md`. `package.json` is unchanged: the middleware uses Node's `crypto` module and nothing else.

The description explains the two places an id can be lost, Koa's default error handler and a transporter that never sees the context, and quotes the `mocha` and `eslint` output from the run. The commands and their full output are in the transcript at `GET /o/{org}/sessions/{id}/messages`.

Before merging, a reviewer decides whether the incoming header should be trusted at all: behind a load balancer that sets its own id it should, and on a service exposed directly it may be better to always generate. A follow-up message to the same session can switch that default, change the header name to `X-Correlation-Id`, or add the id to a `pino` or `winston` logger if the app uses one.

## Run it on every Koa service whose logs cannot be tied to one request

A team with several Koa services sends one `POST /o/{org}/sessions` per repository, this prompt as `input` and the repository in `resources`. Each run reads its own `app.js` files, so a service that already has an error-handling middleware gets the header re-set there, and one that uses a different logger gets the id in that logger's format.

Send a `request_id` that is a UUID v5 of the repository's full name, so a script that runs twice returns the run it already started. The key's `webhook_url` receives `run.completed` with `session_url` for each run the key starts, so a short script can collect every pull request link.

## Why run it on Rush?

A request id is easy to add and easy to lose: the header set at the top of the chain vanishes on a 500, the logger that should print it never sees the context, and nobody notices until the first incident. The agent reads the exact middleware order and the error path in each file, and proves the header survives an error with a test that runs in its own sandbox.

The run keeps the `mocha` and `eslint` output beside the diff, so the pull request shows the four new assertions passing rather than asking a reviewer to start the app and throw an error by hand. Several services can be done at once, each in its own sandbox with its own pull request.

## Frequently asked questions

### Does it trust the X-Request-Id my load balancer sends?

Yes, when the value is short and made of letters, digits, dashes and underscores; anything else is replaced with a generated id. That keeps a proxy's id end to end while stopping a client from writing arbitrary text into your logs. Say in the prompt if you want incoming ids ignored entirely.

### Why not install koa-requestid or a similar package?

The middleware is a dozen lines over Node's `crypto` module, and the repository has no other runtime dependency for cross-cutting concerns. If you prefer a package, name it in the prompt and the agent wires it with the same tests.

### Why randomBytes rather than randomUUID?

`package.json` says `node >= 7.6`, and `crypto.randomUUID` arrived much later. `randomBytes(16).toString('hex')` works on every version the field allows. If you raise the engines field, the agent can switch to a UUID in the same pull request.

### Will the id appear on error responses?

Yes. Koa's default handler removes every response header before writing its 500 and then applies `err.headers`, so the middleware catches, puts `X-Request-Id` on `err.headers` and rethrows. One test sends a request to the `errors` example and asserts the header is on the 500.

### Does it work with pino or winston?

The id lives on `ctx.state.requestId`, so any logger that is called with the context can include it. The agent changes the loggers it finds in the repository; tell it which logger your app uses and it adds the id as a field there.

## More Koa jobs

- [Add Request Timeouts to a Koa App](https://getrush.ai/run/add-request-timeouts/koa/)
- [Add Security Headers to a Koa App](https://getrush.ai/run/add-security-headers/koa/)
- [Add Soft Delete to a Koa API](https://getrush.ai/run/add-soft-delete/koa/)

## The same job on other stacks

- [Add Request ID Logging to a Ktor Server](https://getrush.ai/run/add-request-id-logging/ktor/)
- [Add Request ID Logging to a Leptos App on Axum](https://getrush.ai/run/add-request-id-logging/leptos/)
- [Add Request ID Logging to a Litestar App](https://getrush.ai/run/add-request-id-logging/litestar/)

## Keep reading

- [How a Rush run works on your repository, from request to pull request](https://getrush.ai/cloud/)
- [Compare cloud agents, agent sandboxes and AI code review](https://getrush.ai/compare/)
- [Rush pricing: Free, Pro and Max](https://getrush.ai/pricing/)
