What the agent does
The agent reads how requests enter the app before adding anything to the path. In a NestJS API like lujakob/nestjs-realworld-example-app, src/main.ts creates the app from ApplicationModule with cors: true, sets the global prefix api, mounts Swagger at /docs and listens on 3000; index.js boots it through ts-node/register. package.json pins @nestjs/common and @nestjs/core at 7.0.5 and typescript at 3.8.3, with jest 25 configured in jest.json to run src/**/*.spec.ts through ts-jest, and supertest 3.4.2 as a dev dependency. Middleware is already the pattern for cross-cutting work: AuthMiddleware in src/user/auth.middleware.ts is applied per route in the configure methods of UserModule and ArticleModule. There is no logging anywhere, and ApplicationModule does not yet implement NestModule.
The agent adds src/shared/request-id.middleware.ts, a NestMiddleware that reads an incoming X-Request-Id header if a gateway set one, otherwise generates an id with Node's built-in crypto module (the crypto package listed in package.json is the deprecated npm placeholder and is left alone), stores it on the request, and sets it on the response before any handler runs. ApplicationModule gains a configure(consumer) that applies it to every route, so it runs before AuthMiddleware on the routes that use it and before the controllers everywhere else. The header is echoed on every response, including the 401 that AuthMiddleware throws and the 400 the custom ValidationPipe in src/shared/pipes/validation.pipe.ts raises, because both happen after the middleware has set it.
Logging uses Logger from @nestjs/common, which the version in use already provides, rather than a new dependency. A LoggingInterceptor registered as a global interceptor in ApplicationModule logs one line per request on completion with the method, URL, status, elapsed milliseconds and the request id, and one line at error level when a handler throws, carrying the id and the exception's status so a 401 from the token check and a 500 from a database error are distinguishable in the log. The request id is also added to the body of unhandled errors through a small exception filter, so a client reporting a failure can quote the id the operator will find in the log.
Tests go where jest.json finds them. The one existing spec, src/tag/tag.controller.spec.ts, imports TypeOrmModule.forRoot() and so needs the MySQL database from ormconfig.json; the new tests avoid that. request-id.middleware.spec.ts calls the middleware with plain request and response objects and asserts a header is generated, an incoming one is preserved, and the response carries it. request-id.e2e.spec.ts builds a Nest testing module with only AppController, the middleware and the interceptor, no TypeORM, and uses supertest to check the header on GET /api and on a 404. The agent runs npm test, checks the TypeScript 3.8 compiler accepts the new files through npm run prestart:prod, which runs tsc, and opens the pull request with a sample log excerpt.
Start it with one API call
POST https://api.phoenix.so/o/{org}/sessions with this body:
{
"agent": "codex",
"input": "Add request ID logging to this NestJS API and open a pull request. Read package.json, jest.json, tsconfig.json, index.js, src/main.ts, src/app.module.ts, src/app.controller.ts, src/user/auth.middleware.ts, src/user/user.module.ts, src/article/article.module.ts, src/shared/pipes/validation.pipe.ts, src/shared/base.controller.ts and src/tag/tag.controller.spec.ts first. Add src/shared/request-id.middleware.ts, a NestMiddleware that reuses an incoming X-Request-Id header or generates one with Node's built-in crypto module, stores it on the request and sets it on the response. Make ApplicationModule implement NestModule and apply it to every route so it runs before AuthMiddleware. Add a LoggingInterceptor using Logger from @nestjs/common, registered globally, that logs method, URL, status, elapsed time and the request id per request, and an error line with the id and status when a handler throws; add a small exception filter that puts the request id in unhandled error bodies. Do not add a logging dependency and do not touch the npm crypto placeholder package. Write src/shared/request-id.middleware.spec.ts with plain request and response objects, and an e2e spec that builds a testing module with only AppController, the middleware and the interceptor, no TypeORM, and checks the header with supertest on GET /api and on a 404. Run npm test and npm run prestart:prod to compile with the pinned TypeScript 3.8, fix what they report, and open a pull request with a sample log excerpt.",
"resources": [
{
"url": "https://github.com/your-org/your-app"
}
]
}- 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.
- 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.
- 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
The result is a pull request on its own branch with three new files under src/shared/, two new spec files, a changed src/app.module.ts and no change to package.json. The description shows a sample of the log for a successful GET /api/articles and a failed POST /api/users/login, explains the header contract (reuse if present, generate otherwise, always echo), and notes that the Swagger document at /docs is unaffected.
The transcript keeps the npm test run, in which the two new specs pass without a database while the existing tag.controller.spec.ts still needs one, and the tsc compile under TypeScript 3.8.3. GET /o/{org}/p/{project}/sessions/{id}/changes returns the diff per file.
A reviewer checks that the middleware is registered for every route rather than the subset UserModule and ArticleModule list for authentication, that the interceptor never logs the Authorization header or request bodies, and that the error filter preserves the existing {errors: ...} body shape the controllers throw, adding the id beside it rather than replacing it.
Run it on every API with no request ids
This is a change to start and come back to. 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 the repository, carry on with your own work, and read the pull request later through get_session; wait_for_sessions blocks up to 50 seconds per call when you would rather wait. The sandbox parks after the turn, so a send_session_message asking to also log the user id once AuthMiddleware resolved it wakes the same clone with its node_modules in place.
From a script, send POST /o/{org}/sessions once per NestJS service that lacks request ids, with the repository in resources. A webhook_url on the key receives run.completed with data.session_url for each run it started, so a handler can collect the pull request links.
The use case this job follows, with its automation and trigger: Hand off a long task.
Why run it on Rush?
Request ids are the first thing an on-call engineer wants and the last thing anyone adds by hand, because the change is spread across a middleware, an interceptor, a filter and tests, in a codebase pinned to a NestJS and TypeScript version from 2020 that modern examples do not match. The agent reads the versions in package.json and writes against them, compiles with the pinned tsc, and proves the header on real HTTP requests with supertest in its own sandbox before the pull request exists.
The result carries its own evidence: the test output and the compile are in the transcript, and the pull request shows the log lines a reader will see in production. Several services get the same contract from the same request, one sandbox and one pull request each.
Frequently asked questions
Why middleware rather than an interceptor for the id?
Because an interceptor runs after guards and middleware, so a 401 from AuthMiddleware would leave without an id. Middleware registered in ApplicationModule.configure runs first on every route, which is also the pattern the repository already uses for authentication in UserModule and ArticleModule.
Does it add a logging library?
No. Logger from @nestjs/common 7.0.5 is already in the dependency tree and writes timestamped lines with a context, which is enough for one line per request and one per error. Swapping it for pino or winston later is a change inside the interceptor alone.
Will the existing tag test still need a database?
Yes, unchanged: tag.controller.spec.ts imports TypeOrmModule.forRoot() and reads ormconfig.json. The new specs deliberately build a testing module without TypeORM so they run anywhere npm test runs, and the pull request notes which of the three specs needs MySQL.
What if a gateway already sets X-Request-Id?
The middleware keeps it and echoes it, generating one only when the header is absent, so ids stay consistent across the proxy and the API logs. The unit spec covers both branches.
Does the request id appear in error responses?
Yes, for unhandled errors, through a small exception filter that adds it beside the existing errors body the controllers throw, without changing that shape. A client can then quote the id when reporting a failure.
More NestJS jobs
The same job on other stacks
- Add Request ID Logging to a Quarkus API (Quarkus)
- Add Request ID Logging to a React Router App (React Router)
- Add Request ID Logging to a Rocket App (Rocket)