All jobs

Add Request IDs and Structured Logging to a Fastify App

Yes. An agent makes your Fastify app accept or generate an X-Request-Id, echo it on every response and carry it on error logs, with tests, and opens a pull request.

Run this on RushOpens 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 identified and logged today before it changes either. In an app like fastify/demo, src/server.ts builds the instance with Fastify({ logger: getLoggerOptions(), ... }), where the logger goes through pino-pretty with translateTime and ignore: 'pid,hostname' when stdout is a TTY and otherwise logs at LOG_LEVEL or silent, and sets connection, request, keep-alive and headers timeouts and the Ajv options. It passes no requestIdHeader and no genReqId, so every request gets Fastify's default per-process counter id and an X-Request-Id a gateway sends is ignored. src/app.ts sets an error handler that logs with fastify.log.error, the instance logger, an object with err and the request's method, url, query and params, so the one log line a reviewer needs after an incident carries no request id at all; its not-found handler, by contrast, logs through request.log.warn, which pino binds to the request id. test/helper.ts builds Fastify() with no options for every test, and test/app/error-handler.test.ts builds its own fastify() and asserts the exact error body, { message: 'Internal Server Error' }.

The change is a shared options module, a plugin and one logging call. src/request-id.ts exports the options both the server and the tests need: requestIdHeader set to x-request-id, requestIdLogLabel set to requestId, and a genReqId that returns randomUUID() from node:crypto. Because the incoming header is logged on every line, the module also exports a guard that accepts a client-supplied value only when it is at most 128 characters of letters, digits, dot, underscore and dash, and otherwise generates a fresh id; genReqId receives the raw request, so the guard runs there. src/server.ts spreads those options into Fastify(...), and test/helper.ts does the same so every test sees the production behaviour. A new src/plugins/external/request-id.ts, a fastify-plugin named request-id, adds an onRequest hook that sets reply.header('x-request-id', request.id), which puts the id on every response the app sends: the 401 from src/routes/api/autohooks.ts, the 404 and 429 from the not-found handler and the limiter, and the 500 from the error handler. In src/app.ts the error handler switches from fastify.log.error to request.log.error, so the error line carries requestId beside err; the body stays { message }, because the existing test pins it and a client can read the id from the header.

Tests follow test/helper.ts and the two handler tests. test/app/request-id.test.ts builds the app, requests / and asserts the response carries an x-request-id in UUID form; sends a request with x-request-id set to a short token and asserts the same token comes back; sends one with a 300-character value and asserts a fresh UUID instead; and requests /this-route-does-not-exist to see the header on a 404. For the log, it follows error-handler.test.ts: a fastify({ logger: { stream } }) with a writable that collects lines, fp(serviceApp) registered, a route that throws, one request, and an assertion that the parsed error line has a requestId equal to the response header and a msg of Unhandled error occurred. npm test runs the seed and c8 npm run test:run over ./test/**/*.ts with tsx --test, so the agent starts the mysql:8.4 from docker-compose.yml, runs npm run db:create and npm run db:migrate, and runs the suite with CAN_SEED_DATABASE=1 and RATE_LIMIT_MAX=4 as .github/workflows/ci.yml does on Node 22 and 24, plus npm run build -- --noEmit and npm run lint.

The last step is to see a real line. The agent starts the server with npm run dev with LOG_LEVEL=info, sends a request with a header, reads the JSON log line with its requestId and the response header, and puts both in the pull request. README.md gets two sentences under the server section saying which header to send and which log field to grep.

Start it with one API call

POST https://api.phoenix.so/o/{org}/sessions with this body:

{
  "agent": "claude",
  "input": "Add request ids and structured request logging to this Fastify app. Read package.json, src/server.ts, src/app.ts, src/routes/api/autohooks.ts, every file under src/plugins/external, test/helper.ts, test/app/error-handler.test.ts, test/app/not-found-handler.test.ts and .github/workflows/ci.yml first. Add src/request-id.ts exporting the instance options requestIdHeader x-request-id, requestIdLogLabel requestId, and a genReqId that keeps a client-supplied id only when it is at most 128 characters of letters, digits, dot, underscore and dash and otherwise returns randomUUID from node:crypto; spread those options into Fastify() in src/server.ts and in test/helper.ts. Add src/plugins/external/request-id.ts as a named fastify-plugin with an onRequest hook that sets the x-request-id response header to request.id. In src/app.ts, change the error handler to log through request.log.error so the error line carries the request id, and keep the error body unchanged. Add test/app/request-id.test.ts covering a generated UUID on a plain request, an echoed client id, a replaced overlong id, the header on a 404, and, with a logger stream in the style of error-handler.test.ts, an error line whose requestId equals the response header. Start MySQL from docker-compose.yml, run npm run db:create and npm run db:migrate, then npm test with CAN_SEED_DATABASE=1 and RATE_LIMIT_MAX=4, npm run build -- --noEmit and npm run lint. Start the server with LOG_LEVEL=info, send one request with a header and keep the log line. Add two sentences to the README. Do not add a logging library, do not change the rate limit, under-pressure or session configuration, .env.example or any workflow. Open a pull request that lists the files, explains the header guard, and quotes the test and lint output with the real log line.",
  "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 on its own branch that adds src/request-id.ts, src/plugins/external/request-id.ts and test/app/request-id.test.ts, and changes src/server.ts, src/app.ts, test/helper.ts and README.md. The body lists the files, explains the guard on client-supplied ids and why the error body is unchanged, and quotes the npm test summary with its coverage table, the type check, the lint, and one real JSON log line with its requestId beside the matching response header.

The session read names the repository and the pull request, and the transcript keeps the MySQL start, the migrations, the seed, the first test run in which the new tests failed, the passing run, the lint, and the request to the running server. GET /o/{org}/p/{project}/sessions/{id}/changes lists the files with their diff.

Before merging, a reviewer checks that test/helper.ts and src/server.ts take their options from the same module so tests cannot drift from production, that the guard bounds the length and the character set of an incoming id since the value reaches every log line, that the 401, 404, 429 and 500 paths all carry the header, and that no dependency was added.

Run it on every Fastify service without request ids

Request ids are a hand-off job: well specified, mostly reading, and the same on every service. From Claude Code or Codex with Rush connected as an MCP server at https://api.phoenix.so/mcp, ask for a create_session with this prompt and your repository, keep working, and read the pull request later with get_session; wait_for_sessions waits up to 50 seconds per call when you would rather block. The sandbox parks with node_modules and the database when the turn ends, so a send_session_message asking for the id in the error body as well wakes it where it stopped.

From a script, send one POST /o/{org}/sessions per Fastify service with the repository in resources and a request_id per repository, so a retried call returns the run it already started. With a webhook_url on the key, each run the key started POSTs run.completed, run.failed or run.cancelled when its turn ends, with data.session_url to read for the pull request link.

The use case this job follows, with its automation and trigger: Hand off a long task.

Why run it on Rush?

The mistake in this job is subtle: an id configured only in src/server.ts is invisible to a test suite whose helper builds a bare Fastify(), and an error handler that logs through the instance logger produces the one line that has no id, exactly where the id matters. The agent reads the helper and the handlers in its own sandbox, moves the options into a module both sides import, and proves the error line with a captured log stream against the seeded test suite and the repository's own MySQL.

The pull request carries a real log line and a real header from the running server beside the test and lint output, and adds no dependency, since pino and Fastify already do the work once configured. Several services get the same change at once, each in its own sandbox and pull request, with each one's server and helper files read rather than assumed to match the demo.

Frequently asked questions

Does it add a logging library?

No. Fastify's built-in pino logger binds the request id to request.log once requestIdLogLabel is set, and the error handler only has to log through request.log instead of fastify.log. The pino-pretty transport the app already uses on a TTY shows the same field.

What if a gateway already sets X-Request-Id?

The id is kept when it passes the guard, at most 128 characters of letters, digits, dot, underscore and dash, and echoed on the response, so a proxy's correlation id survives into the logs. A value outside that shape is replaced by a UUID, because the header is written to every log line and should not carry arbitrary input.

Why keep the error body as it is?

test/app/error-handler.test.ts asserts the exact { message: 'Internal Server Error' } body, and a client can read the id from the response header on every status. Adding the id to the body is a follow-up on the same session if your clients prefer it, with that test updated in the same change.

Do the existing tests still pass with the new options?

Yes, that is why test/helper.ts spreads the same options the server uses: the suite then exercises the header guard and the UUID generation on every request, and the rate-limit, not-found and route tests keep their assertions.

More Fastify jobs

The same job on other stacks

Keep reading