# Add Request ID Logging to an AdonisJS App

Yes. An agent uses the request id AdonisJS 6 already generates, returns it as X-Request-ID, logs one line per request with it, tests both, and opens a PR.

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

## What the agent does

The agent reads what the framework already does before adding a middleware, because in AdonisJS most of this job is a setting that is already on. In an app started from the `api` kit in adonisjs/starter-kits, `package.json` depends on `@adonisjs/core` ^7.5.2 with `@adonisjs/auth`, `@adonisjs/cors`, `@adonisjs/lucid`, `@adonisjs/session` and `@adonisjs/shield`, and uses Japa with `@japa/api-client` for tests through `node ace test`. `config/app.ts` sets `generateRequestId: true` and `useAsyncLocalStorage: false`. `config/logger.ts` builds a pino logger named from `APP_NAME` at `LOG_LEVEL`, writing to file descriptor 1. `start/kernel.ts` registers three server middleware, `force_json_response`, `container_bindings`, which binds `Logger` to `ctx.logger`, and CORS, then the router middleware for the body parser, session, shield and auth. `start/routes.ts` has `GET /` returning `{ hello: 'world' }` and the `/api/v1` auth and account routes.

Reading `@adonisjs/http-server` shows what that setting gives for free. `Request.id()` returns the incoming `x-request-id` header, and when none is present and `generateRequestId` is on it creates one with `crypto.randomUUID()` and writes it into the request's headers so later reads agree. When the server builds the `HttpContext` it creates `ctx.logger` as `logger.child({ request_id: request.id() })`, so every line written through `ctx.logger`, including what the exception handler's `report` writes, already carries the id. What is missing is the two sides a person needs: the client never sees the id, since nothing sets a response header, and no line is written per request, so a log viewer has the id on errors but nothing to correlate a successful request with.

The agent adds `app/middleware/request_id_middleware.ts` and registers it first in `server.use` in `start/kernel.ts`, ahead of `force_json_response`, so it wraps every request including ones with no matching route. It reads `ctx.request.id()`, sets `x-request-id` on the response, records the start time, awaits `next()`, and in a `finally` logs one `info` record through `ctx.logger` with `method`, `url`, `status` from `response.getStatus()` and `duration_ms`; because `ctx.logger` is the child, `request_id` is on that record without being passed. `useAsyncLocalStorage` stays off: the pull request explains that turning it on lets code outside a controller call `HttpContext.get()` and log with the id, at a small cost per request, and leaves that as the team's choice. The exception handler is untouched, since its reports already go through `ctx.logger`.

Tests go in a new `tests/functional/request_id.spec.ts`, since `adonisrc.ts` already defines the `functional` suite. With the api client it requests `GET /` and asserts a `x-request-id` response header matching a UUID pattern, sends a second request with `x-request-id: abc-123` and asserts the same value is returned, and requests an unknown path to show the header is present on a `404` too. A unit test builds a context with `testUtils.createHttpContext()`, swaps `ctx.logger` for a pino instance writing to a buffer, runs the middleware around a stub `next`, and asserts one record with `request_id`, `status` and `duration_ms`. In the sandbox the agent installs dependencies, runs `npm run typecheck`, `npm run lint` and `node ace test`, starts `node ace serve`, shows `curl -i` on `/` with the header and the matching log line, and opens the pull request.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add request id logging to this AdonisJS app. Read package.json, adonisrc.ts, config/app.ts, config/logger.ts, start/kernel.ts, start/routes.ts, start/env.ts, app/middleware/container_bindings_middleware.ts, app/exceptions/handler.ts, tests/bootstrap.ts and .env.example first, and read Request.id() and the HttpContext construction in @adonisjs/http-server under node_modules to confirm that generateRequestId already yields a UUID and that ctx.logger is a child with request_id. Add app/middleware/request_id_middleware.ts that sets x-request-id on the response from ctx.request.id(), awaits next, and in a finally logs one info record through ctx.logger with method, url, status from response.getStatus() and duration_ms; register it first in server.use in start/kernel.ts. Leave useAsyncLocalStorage off and explain in the pull request what turning it on would add. Add tests/functional/request_id.spec.ts asserting a UUID-shaped x-request-id on GET /, the same value back when x-request-id abc-123 is sent, and the header on a 404, plus a unit test with testUtils.createHttpContext() and a pino logger on a buffer asserting one record with request_id, status and duration_ms. Install dependencies, run npm run typecheck, npm run lint and node ace test, start node ace serve and curl -i /, then open a pull request that pastes the test output, the curl headers and the matching 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 that adds `app/middleware/request_id_middleware.ts`, `tests/functional/request_id.spec.ts` and a unit spec, and changes `start/kernel.ts`. The description quotes the two lines from `@adonisjs/http-server` that generate the id and attach it to `ctx.logger`, pastes `curl -i` on `/` with the `x-request-id` header, and the JSON log line whose `request_id` field holds the same UUID beside `method`, `url`, `status` and `duration_ms`.

The run's record holds the install, the type check, the lint and the Japa run with the new functional and unit cases. `config/app.ts`, `config/logger.ts`, the routes, the controllers and the exception handler are untouched; the only wiring change is one entry at the top of `server.use`.

Before merging, a reviewer decides whether to trust an incoming `x-request-id` from any client or only from the proxy in front of the app, since `Request.id()` keeps whatever it receives, whether the access record belongs at `info` or `debug` on a busy API, and whether to turn on `useAsyncLocalStorage` so services and jobs can log with the id without receiving the context.

## Run it on every new AdonisJS service

A team with several AdonisJS services starts one run per repository from its own server: one `POST /o/{org}/sessions` each, with that repository in `resources` and a `request_id` that is a UUID v5 of the repository's full name, so a retried call returns the run already started rather than a second pull request. Each run reads that service's own `config/app.ts`, so a service with `generateRequestId` off gets it turned on first and a service already behind a proxy that sets the header gets only the echo and the access record.

Afterwards, an automation on the Project with a `github` trigger on `pull_request.opened` and `pull_request.synchronize` and the prompt "if this pull request adds a middleware before request_id_middleware in start/kernel.ts, or logs through the app logger service instead of ctx.logger inside a request, comment with the line" keeps later code on the correlated logger. The trigger adds the pull request after the prompt; only work by an owner, member or collaborator fires it, never a fork's.

## Why run it on Rush?

The job is mostly reading: the framework already generates the id and binds it to the per-request logger, so the right change is small and the wrong change is a second id generator that disagrees with the one in `ctx.logger`. The agent reads `Request.id()` and the context construction in the installed package, builds on them, and proves with a functional test that the header the client gets is the id the log line carries.

In its own sandbox the agent runs the type check, the lint, the Japa suite and a real server, and the run keeps the headers and the log line for the pull request. For a team with many AdonisJS services, each gets its own run and its own pull request fitted to that service's kernel.

## Frequently asked questions

### Does AdonisJS not already log the request id?

It attaches `request_id` to `ctx.logger`, so any line a controller or the exception handler writes through it carries the id. It does not write a line per request on its own and does not return the id to the client; those are the two pieces the middleware adds, using the same id the framework generated.

### Why register the middleware in server.use and not router.use?

Server middleware runs for every request, including ones that match no route, so a `404` gets the header and the access record too. Router middleware runs only after a route matches. Putting it first in `server.use` also means `duration_ms` covers the whole pipeline.

### What would useAsyncLocalStorage add?

With it on, code that never receives the context, such as a service or a model hook, can call `HttpContext.get()` and reach `ctx.logger`, so its lines carry the id as well. The kit ships with it off and the pull request leaves it off, noting the option and its per-request cost.

### Will the existing exception handler lose anything?

No. `report` in `app/exceptions/handler.ts` calls the base class, which logs through `ctx.logger`, so error records already have `request_id` and now sit beside an access record with the same id and the final status. Nothing in the handler changes.

## More AdonisJS jobs

- [Add Database Seeders to an AdonisJS API](https://getrush.ai/run/add-seed-data/adonisjs/)
- [Write Japa Tests for an AdonisJS API](https://getrush.ai/run/write-japa-tests/adonisjs/)
- [Add Account Deletion to an AdonisJS API](https://getrush.ai/run/add-account-deletion/adonisjs/)

## The same job on other stacks

- [Add Request ID Logging to an aiohttp App](https://getrush.ai/run/add-request-id-logging/aiohttp/)
- [Add Request ID Logging to a chi App](https://getrush.ai/run/add-request-id-logging/chi/)
- [Add Request ID Logging to a Cloudflare Worker](https://getrush.ai/run/add-request-id-logging/cloudflare-workers/)

## 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/)
