# Add Request ID Logging to a Cloudflare Worker

Yes. An agent gives every request through your Worker an id, returns it in a header, writes one JSON log line per request for Workers Logs, and opens a PR.

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

## What the agent does

The agent reads the Worker before it adds a line of logging. In a Worker like `nodejs-http-server-template` in cloudflare/templates, `wrangler.jsonc` names the Worker, points `main` at `src/index.ts`, sets `compatibility_date` to `2025-10-08` with the `nodejs_compat` flag, turns `observability` on and uploads source maps. `src/index.ts` builds a server with `createServer` from `node:http`, answers `/` with HTML, `/api/status` with a JSON body of `status` and `timestamp`, and anything else with a plain `404`, then calls `server.listen(8080)` and exports `httpServerHandler({ port: 8080 })` from `cloudflare:node`. `package.json` pins `wrangler` `4.136.1`, `typescript` `5.9.3` and `@types/node` `24.10.1`, with a `check` script that runs `tsc && wrangler deploy --dry-run` and no test script. Nothing logs today, so a request that fails leaves no trace a developer can search for.

Because the Worker uses the Node HTTP server API, the agent wraps the request listener rather than touching each route. It adds `src/request-id.ts` with one pure function that takes the incoming headers and returns an id: the caller's `x-request-id` when it is present and matches a conservative pattern of up to 64 URL-safe characters, otherwise a fresh `crypto.randomUUID()`. The listener in `index.ts` calls it first, sets `x-request-id` on the response before any `writeHead`, records `performance.now()`, and on the response's `finish` event writes a single `console.log(JSON.stringify({...}))` with the id, the `cf-ray` header Cloudflare adds, the method, the path, the status code and the duration in milliseconds. With `observability` already enabled in `wrangler.jsonc`, Workers Logs indexes those JSON fields, so a developer can filter on `requestId` in the dashboard or `wrangler tail` and see the one line for a failed call.

The agent adds `vitest` as a dev dependency with a `test` script and writes `src/request-id.test.ts` covering the three cases: a valid incoming id is echoed, an oversized or odd-character id is replaced, and no header yields a UUID. It leaves the three routes and their bodies as they are, so the `/api/status` response does not change shape for existing callers, and it does not add a logging library, because one `console.log` of a JSON string is what Workers Logs wants.

Before pushing, the agent runs `npm ci`, `npm run check`, which type-checks and performs a dry-run deploy to show the bundle still builds under `nodejs_compat`, and `npx vitest run`. It then starts `wrangler dev` in its sandbox, sends requests to `/`, `/api/status` and a missing path with and without an `x-request-id` header, shows the header on each response and the JSON line `wrangler dev` prints for each, and quotes those in 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 Cloudflare Worker and open a pull request. Read wrangler.jsonc, package.json, tsconfig.json, worker-configuration.d.ts and src/index.ts first. Add src/request-id.ts with a pure function that returns the incoming x-request-id when it is at most 64 URL-safe characters and otherwise a fresh crypto.randomUUID(). In the request listener, set x-request-id on every response before writeHead and, on the response finish event, write one console.log of a JSON string with the request id, the cf-ray header, method, path, status and duration in milliseconds, so Workers Logs indexes the fields. Do not change the routes or their bodies and do not add a logging library. Add vitest with a test script and tests for the echoed, replaced and generated id cases. Run npm run check and the tests, then start wrangler dev and show the header and the log line for each route with and without an incoming id. Quote the outputs in the 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 on its own branch that changes `src/index.ts` to wrap the listener, adds `src/request-id.ts` and `src/request-id.test.ts`, and changes `package.json` and `package-lock.json` to add `vitest` and a `test` script. The description shows a sample log line, explains the header contract, and names the dashboard filter a developer types to find a request by id.

The proof is the output of `npm run check` and `npx vitest run`, and the `wrangler dev` session with the curl responses showing `x-request-id` on each and the JSON line printed for each, all quoted in the description and kept in the run's record. Whatever workflow the repository runs on pull requests runs here as well. No deploy is claimed; `wrangler deploy --dry-run` only shows that the bundle builds.

Before merging, a reviewer checks that trusting an incoming `x-request-id` is wanted, since a client can then choose the value that appears in logs, that the log line holds no header a privacy review would object to, and that the field names match any convention their other services use. Then they deploy and filter Workers Logs on one id from a real request.

## Run it on every Worker without request logging

A team with several Workers sends one `POST /o/{org}/sessions` per repository, with this prompt and the repository in `resources`. `GET /o/{org}/github` lists every repository the Rush GitHub App installation can reach, so a script can start a run for each one with a `wrangler.jsonc` or `wrangler.toml` and no `x-request-id` in its source. Each run reads that Worker's own entry point, so a Hono Worker gets a middleware and a plain `fetch` handler gets a wrapper around the handler, and each opens its own pull request.

Set a webhook URL on the API key and Rush POSTs `run.completed` or `run.failed` when a run's turn finishes, with `session_url` so your server can read the pull request link. Send a fresh UUID as `request_id` with each request so a retry returns the run already started.

## Why run it on Rush?

Adding an id and a log line is small, and the questions around it are what take the time: where to set the header so it survives `writeHead`, when the `finish` event fires relative to the status being known, what Workers Logs will index and what it will flatten, and whether the bundle still builds under `nodejs_compat` once `node:crypto` or the global `crypto` is in play. On Rush the agent answers those by running `wrangler dev` in its own sandbox and sending real requests, so the pull request shows the header and the log line rather than describing them.

Every command, response and log line stay in the run's record, the diff is three small files plus the lockfile, and nothing deploys until a person merges. The same request can add the same contract to every Worker a team runs, one sandbox and one pull request each, so request ids line up across services.

## Frequently asked questions

### Why accept the caller's x-request-id at all?

So a request can be traced across services: a front-end or gateway that already sets the header gets the same id back and in this Worker's logs. The agent bounds it to 64 URL-safe characters so a client cannot inject newlines or a very long string into the log line. If you would rather always generate the id, say so in the prompt and the function shrinks to one line.

### Does this need a logging library?

No. Workers Logs, enabled by `observability` in `wrangler.jsonc`, parses a `console.log` of a JSON string into fields you can filter on. A library would add bundle size and another API to learn for a single line per request.

### What about the cf-ray header?

Cloudflare attaches a `cf-ray` value to every request at the edge, and the log line records it beside the request id, so a support ticket that quotes a Ray ID from an error page can be matched to the application's own id. The Worker does not change or return `cf-ray`.

### Will the test run the Worker itself?

The Vitest tests cover the id function, which is where the decisions are. The end-to-end check is the `wrangler dev` session in the sandbox, with the curl output in the pull request. If you want tests that run the Worker in `workerd`, ask for `@cloudflare/vitest-pool-workers` in the prompt and the agent adds that configuration too.

## More Cloudflare Workers jobs

- [Add a JSON REST API Over D1 to a Cloudflare Worker](https://getrush.ai/run/add-rest-api/cloudflare-workers/)
- [Add Security Headers to a Cloudflare Worker](https://getrush.ai/run/add-security-headers/cloudflare-workers/)
- [Add a Staging Environment to a Cloudflare Worker](https://getrush.ai/run/add-staging-environment/cloudflare-workers/)

## The same job on other stacks

- [Add Request ID Logging to a CodeIgniter 4 App](https://getrush.ai/run/add-request-id-logging/codeigniter/)
- [Add Request ID Logging to an Echo App](https://getrush.ai/run/add-request-id-logging/echo/)
- [Add Request ID Logging to a FastAPI App](https://getrush.ai/run/add-request-id-logging/fastapi/)

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