# Add Request ID Logging to a tRPC API

Yes. An agent gives every tRPC call a request id from the context, logs one JSON line per procedure with it, returns it as a header, tests it and opens a PR.

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

## What the agent does

A tRPC app has two places a request passes through, the Next.js API route and the procedure middleware, and the agent reads both before deciding where the id is born. In an app laid out like trpc/examples-next-prisma-starter, `src/pages/api/trpc/[trpc].ts` calls `createNextApiHandler` with the `appRouter`, a `createContext` and an `onError` hook that only `console.error`s when `error.code` is `INTERNAL_SERVER_ERROR`. `src/server/context.ts` is the empty shell the starter ships: `createContextInner` takes a `CreateContextOptions` with its one field commented out and returns `{}`, and `createContext` receives `CreateNextContextOptions`, which carries `req` and `res`, and ignores them. `src/server/trpc.ts` builds `initTRPC.context<Context>().create()` with the superjson `transformer` and an `errorFormatter` that returns the shape unchanged, and exports `router`, `publicProcedure`, `mergeRouters` and `createCallerFactory`; there is no `t.middleware` anywhere yet. `src/server/routers/_app.ts` mounts a `healthcheck` query and the `post` router, whose `list`, `byId` and `add` procedures in `post.ts` go to Prisma 6 against Postgres. The client in `src/utils/trpc.ts` uses `httpBatchStreamLink`, so one HTTP request to `/api/trpc` can carry several procedure calls, and it forwards the browser's headers during server-side rendering.

The id is created in the context, because that is the one object every procedure in a batch shares. The agent extends `CreateContextOptions` with a `requestId: string`, has `createContext` read `opts.req.headers['x-request-id']` when a proxy or load balancer already set one and otherwise call `crypto.randomUUID()` from `node:crypto`, and sets the same value on `opts.res` as an `x-request-id` response header so a client can quote it. `createContextInner` passes it through, which keeps `src/server/routers/post.test.ts` working: that Vitest test calls `createContextInner({})` and then `createCaller(ctx)`, so the agent gives it a fixed id in the test and leaves the call site otherwise alone. `Context` is inferred from `createContextInner`'s return type, so every procedure now sees `ctx.requestId` with no further typing.

Logging happens in a middleware so no router changes. In `src/server/trpc.ts` the agent adds `const loggedProcedure = t.procedure.use(async ({ path, type, ctx, next }) => …)`, which records `performance.now()` before `next()` and afterwards writes one JSON line with `requestId`, `path` (`post.list`, `post.byId`), `type` (`query` or `mutation`), `durationMs` and `ok`, through a small `src/server/log.ts` that `JSON.stringify`s the fields and writes to stdout, so it reads the same under `next dev` and under a log shipper. `publicProcedure` is re-pointed at `loggedProcedure` and `post.ts` and `_app.ts` do not change. The `onError` hook in `[trpc].ts` receives `ctx` and `path`, so the agent makes its error line carry the same `requestId` and `path` instead of a bare `console.error`, and extends it past `INTERNAL_SERVER_ERROR` to log every error code at warning level with the message, since a `NOT_FOUND` from `post.byId` is exactly what a support thread asks about. Because a batch shares one context, several lines carry the same id, one per procedure, which the pull request calls out.

Then the agent proves it. It starts Postgres in its sandbox as `.github/workflows/main.yml` does, with the `trust` auth method and the `trpcdb` database, sets `DATABASE_URL` as `.env` shows, runs `pnpm install`, which triggers `pnpm generate` from the `postinstall` script, then `pnpm prebuild` to generate and migrate, and `pnpm test-unit`, where `vitest.config.mts` loads `dotenv/config` and maps `~/` to `src/`. It adds a second Vitest test that calls `post.list` through `createCaller` with a known id and asserts the captured log line parses as JSON with that `requestId`, `path` set to `post.list` and `type` set to `query`. It runs `pnpm lint`, which is `eslint --cache src`, and `pnpm typecheck`, and finishes with `pnpm build` so the `next build` that CI runs is known to pass with the new context type.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add request id logging to this tRPC app. Read src/pages/api/trpc/[trpc].ts, src/server/context.ts, src/server/trpc.ts, src/server/routers/_app.ts, src/server/routers/post.ts, src/server/routers/post.test.ts, src/utils/trpc.ts, vitest.config.mts, .env and .github/workflows/main.yml first. In createContext, take x-request-id from the incoming request when present and otherwise make one with crypto.randomUUID(), put it on the context as requestId, and set it as the x-request-id response header. Add a tRPC middleware in src/server/trpc.ts that logs one JSON line per procedure call to stdout with requestId, path, type, durationMs and ok, and make publicProcedure use it; do not change the routers. Make the onError hook in [trpc].ts log every error with the requestId, path and error code. Keep the existing post.test.ts passing by giving createContextInner a fixed requestId, and add a Vitest test that captures the log line for post.list and checks its fields. Start Postgres as the CI workflow does, run pnpm prebuild, pnpm test-unit, pnpm lint, pnpm typecheck and pnpm build, and open a pull request that shows an example log line and the response header.",
  "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

The pull request changes `src/server/context.ts`, `src/server/trpc.ts`, `src/pages/api/trpc/[trpc].ts` and `src/server/routers/post.test.ts`, and adds `src/server/log.ts` and one test file beside `post.test.ts`. The description pastes one log line as the middleware writes it and the `x-request-id` header from a response, and explains that a batched request produces one line per procedure under one id. No router, page or Prisma file changes, and `package.json` gains no dependency.

The repository's `Testing` workflow runs both of its jobs on the pull request: `unit`, which starts the Postgres service, runs `pnpm prebuild`, `pnpm test-unit` and `pnpm tsc`, and `e2e`, which builds and runs the Playwright smoke test against the same database. The run's record keeps the sandbox output of `pnpm test-unit`, `pnpm lint`, `pnpm typecheck` and `pnpm build` so a reviewer can compare them with the checks.

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, which fields the line should carry beyond the five the agent chose, and whether `durationMs` should be rounded. The agent leaves the `errorFormatter` alone, so a client sees no new field on an error; a team that wants the id in the error shape can add it there in a follow-up.

## Run it on every tRPC repository with no request id

An organisation with several tRPC services starts one run per repository from its own server: one `POST /o/{org}/sessions` each, with the 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. Each run reads its own context file, so a service whose `createContext` already reads a session or a header gets the id added beside it, and a service with an Express or Fastify adapter instead of Next.js gets the id taken from that adapter's request object.

A team that wants new services to start with request ids runs this prompt from an automation in the Project with a `github` trigger on `pull_request.opened`, filtered to pull requests that add a file under `src/server/routers/`. The trigger adds the event after the prompt, and the run reads the new router, confirms every new procedure goes through `publicProcedure` and so through the logging middleware, and comments on the pull request with the one that does not.

## Why run it on Rush?

The change is small, but it crosses the context type, a middleware, an error hook and a test, and a mistake in any one is only visible at runtime: a `createContextInner` signature that no longer matches the test, a middleware that returns before `next()` resolves, or an id that differs between the log line and the header. The agent runs `pnpm test-unit`, `pnpm typecheck` and `pnpm build` in its own sandbox against a real Postgres, so what arrives has been exercised, not only typed.

Every command and its output stay with the run, including the `pnpm prebuild` migration and the log line the test captured, so a reviewer who has never opened the repository can see the id flow from header to context to log. Ten services get the same treatment at once, each in its own sandbox with its own database and its own pull request.

## Frequently asked questions

### Why put the id in the context rather than in a Next.js middleware?

Because tRPC batches calls: `httpBatchStreamLink` sends several procedure calls in one HTTP request, and the context is the object all of them share. An id created in `createContext` reaches every procedure in the batch and the `onError` hook, while a Next.js `middleware.ts` runs on the edge and cannot hand a value to the tRPC handler without a header round trip.

### Does this change the response for clients?

Only by adding an `x-request-id` header. The JSON body, the superjson transformer and the error shape are unchanged. A browser client that wants to show the id to a user can read the header from the `httpBatchStreamLink` response; the agent does not add that to `src/utils/trpc.ts`.

### Will my existing post.test.ts keep working?

Yes. It calls `createContextInner({})` and then `createCaller(ctx)`, so the agent gives that call a fixed `requestId` and leaves the assertions alone. The server-side caller never goes through the HTTP handler, so no header is involved in tests.

### Does the middleware slow down procedures?

It adds one `performance.now()` call before and after `next()` and one `JSON.stringify` per procedure. The agent logs `durationMs` so the pull request can show what a `post.list` call costs with and without the line, measured in its own sandbox against a local Postgres.

### What about the Playwright smoke test?

`playwright/smoke.test.ts` loads pages through the browser and is unchanged; CI's `e2e` job runs it after `pnpm build`. The agent runs `pnpm build` in the sandbox to show the build is green, and leaves the browser test to the workflow, which has the Playwright install step.

## More tRPC jobs

- [Add Response Caching to a tRPC API](https://getrush.ai/run/add-response-caching/trpc/)
- [Add Soft Delete to a tRPC and Prisma App](https://getrush.ai/run/add-soft-delete/trpc/)
- [Prefetch tRPC Queries on the Server in a Next.js Pages Router App](https://getrush.ai/run/add-ssr-prefetching/trpc/)

## The same job on other stacks

- [Add Request ID Logging to a Vapor App](https://getrush.ai/run/add-request-id-logging/vapor/)
- [Add Request ID Logging to a Wagtail Site](https://getrush.ai/run/add-request-id-logging/wagtail/)
- [Add a Request ID to Every Winston Log Line in an Express App](https://getrush.ai/run/add-request-id-logging/winston/)

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