# Add Prometheus Metrics to a tRPC API on Next.js

Yes. An agent adds a tRPC middleware that times every procedure into prom-client histograms, serves them at /api/metrics, tests it with Vitest and opens a PR.

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

## What the agent does

The agent reads how procedures are built before it measures them, because tRPC has one place every call passes through and it is not the HTTP handler. In an app laid out like trpc/examples-next-prisma-starter, `package.json` pins `next` `^15.5.25`, `react` 19, the `@trpc/server`, `@trpc/client`, `@trpc/next` and `@trpc/react-query` packages on the `canary` tag of v11, `@prisma/client` `^6.7.0`, `zod` `^4.2.1` and `superjson`, with `vitest` `^5.0.0` and Playwright for tests and `pnpm` as the package manager. `src/server/trpc.ts` calls `initTRPC.context<Context>().create()` with the superjson `transformer` and an `errorFormatter`, and exports `router`, `publicProcedure` as `t.procedure`, `mergeRouters` and `createCallerFactory`. `src/server/routers/_app.ts` has a `healthcheck` query and mounts `postRouter`, whose `list`, `byId` and `add` procedures in `post.ts` call Prisma and throw a `TRPCError` with code `NOT_FOUND` for a missing post. `src/pages/api/trpc/[trpc].ts` wraps the router with `createNextApiHandler` and an `onError` that logs `INTERNAL_SERVER_ERROR` to the console. `src/server/prisma.ts` keeps one `PrismaClient` on `globalThis` outside production so Next's dev reloads do not open a client per reload, and `src/server/env.ts` validates `DATABASE_URL` and `NODE_ENV` with zod.

The agent installs `prom-client` and writes `src/server/metrics.ts` in the same shape as `prisma.ts`: a `Registry` stored on `globalThis` outside production, because `prom-client` throws when a metric name is registered twice and Next's hot reload would do exactly that. It calls `collectDefaultMetrics({ register })` once for the process and memory gauges, and defines a `Histogram` named `trpc_procedure_duration_seconds` with labels `path`, `type` and `ok` and buckets from 5 milliseconds to 10 seconds, plus a `Counter` named `trpc_procedure_errors_total` with labels `path` and `code`. The labels are the procedure path such as `post.byId` and the `TRPCError` code, never any input value, so the label set stays small.

The timing goes into `src/server/trpc.ts` as `t.middleware`: it reads `path` and `type` from the middleware options, records `process.hrtime.bigint()` before `await next()`, observes the elapsed seconds with `ok` set from the result's `ok` field, and on a failed result increments the error counter with the error's `code`, which for the `byId` miss is `NOT_FOUND`. `publicProcedure` becomes `t.procedure.use(metricsMiddleware)`, so every procedure in the app and any router added later is measured without touching `post.ts`. Because a batched request from `@trpc/next` runs several procedures through one HTTP call, measuring at the middleware rather than in `[trpc].ts` gives one observation per procedure, which is what a dashboard wants. The route is `src/pages/api/metrics.ts`, a Pages API handler that answers `await register.metrics()` with `register.contentType`, and refuses with `401` unless the `Authorization` header matches a `METRICS_TOKEN` that the agent adds to `env.ts` as optional; with the variable unset the route is open and the pull request says so.

Tests follow `src/server/routers/post.test.ts`, which builds a caller with `createCaller(await createContextInner({}))`. The new `src/server/metrics.test.ts` calls `caller.healthcheck()` and asserts that `register.getSingleMetricAsString('trpc_procedure_duration_seconds')` contains a `_count` line with `path="healthcheck"`, `type="query"` and `ok="true"`, then calls `caller.post.byId({ id: 'missing' })` inside `expect().rejects` and asserts the error counter has `path="post.byId"` and `code="NOT_FOUND"`. The agent starts PostgreSQL in its sandbox with the `DATABASE_URL` from `.env`, runs `pnpm install`, `pnpm prebuild` for `prisma generate` and `prisma migrate deploy`, then `pnpm test-unit` and `pnpm tsc` as the `unit` job in `.github/workflows/main.yml` does, starts `pnpm dev`, calls `/api/trpc/healthcheck` and `/api/trpc/post.byId` once each and reads `/api/metrics` to capture real histogram and counter lines.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add Prometheus metrics to this tRPC API. Read package.json, src/server/trpc.ts, src/server/routers/_app.ts, src/server/routers/post.ts, src/server/routers/post.test.ts, src/server/context.ts, src/server/prisma.ts, src/server/env.ts, src/pages/api/trpc/[trpc].ts, vitest.config.mts and .github/workflows/main.yml first. Install prom-client and create src/server/metrics.ts with a registry kept on globalThis outside production the way prisma.ts keeps its client, default metrics, a duration histogram labelled by procedure path, type and ok, and an error counter labelled by path and TRPCError code. Add a tRPC middleware in trpc.ts that times each procedure and apply it to publicProcedure so every router is covered. Add src/pages/api/metrics.ts that serves the registry with its content type and checks an optional METRICS_TOKEN from env.ts. Write a Vitest test that calls healthcheck and a missing post.byId through createCaller and asserts the histogram count and the NOT_FOUND counter. Start PostgreSQL, run pnpm install, pnpm prebuild, pnpm test-unit and pnpm tsc, start the dev server, hit two procedures and read /api/metrics, then open a pull request with the real metric lines.",
  "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 `src/server/metrics.ts`, `src/pages/api/metrics.ts` and `src/server/metrics.test.ts`, and changes `src/server/trpc.ts` for the middleware, `src/server/env.ts` for the optional token, `package.json` and `pnpm-lock.yaml` for `prom-client`, and `.env` with a commented `METRICS_TOKEN` line. The description pastes the `/api/metrics` output after the two calls, with the `trpc_procedure_duration_seconds_bucket` lines for `healthcheck` and the `trpc_procedure_errors_total{path="post.byId",code="NOT_FOUND"} 1` line, and the Vitest summary naming the new test.

The `Testing` workflow's `unit` job runs `pnpm test-unit` and `pnpm tsc` against a PostgreSQL service on the pull request, so a reviewer sees the new test and the type check pass on GitHub before merging. The run's record keeps the database start, the Prisma generate and migrate steps, the test run and each `curl`, so every metric line in the description traces to the request that produced it.

Before merging, a reviewer decides whether `/api/metrics` should be open inside their network or require the token, whether the bucket boundaries match their latency targets, and whether to add Prisma's own metrics preview feature to the same registry later. The agent changes no procedure's input or output.

## Run it on every tRPC service onboarded to monitoring

A team with several tRPC apps on this starter 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 `trpc.ts`, so an app with a `protectedProcedure` built from an auth middleware gets the metrics middleware placed before it, and one on the App Router with a `fetchRequestHandler` gets a Route Handler for `/api/metrics` instead of a Pages API file.

After that, an automation in the Project with a `github` trigger on `pull_request.opened` and `pull_request.synchronize` and the prompt "if this pull request adds a procedure built from t.procedure directly rather than publicProcedure or a procedure derived from it, say so in a comment, because it will not be measured" keeps new routers in the histogram. The trigger adds the pull request after the prompt and fires only for work by owners, members and collaborators.

## Why run it on Rush?

Metrics added without running the app go wrong in ways a diff hides: a registry rebuilt on every hot reload that throws a duplicate-metric error on the second save, a label taken from a procedure's input that turns one series into thousands, or a timer in the HTTP handler that reports one number for a batch of five procedures. The agent runs the real server in its sandbox, calls real procedures and reads the real `/api/metrics` text before it opens the pull request.

Every command stays with the run, from the PostgreSQL start to the `curl` of the metrics route, and the pull request quotes them. Instrumenting a dozen tRPC services at once costs no more attention than one, because each run has its own machine, its own record and its own pull request.

## Frequently asked questions

### Why a tRPC middleware instead of timing the Next.js API route?

Because `@trpc/next` batches several procedure calls into one HTTP request, so a timer around `[trpc].ts` would record one duration for the whole batch under one path. `t.middleware` runs once per procedure with its `path` and `type`, which gives one observation per call and a label a dashboard can group by. It also covers a server-side `createCaller`, which never goes through the HTTP route.

### Will the registry break under next dev's hot reload?

Not with the `globalThis` pattern the pull request copies from `prisma.ts`. `prom-client` refuses to register a metric name twice on the same registry, and a module re-evaluated by hot reload would do that; keeping the registry and its metrics on the global object outside production means the second evaluation reuses them. In production the module loads once and the global is not used.

### Is /api/metrics safe to expose?

It lists procedure names, latencies and process memory, which is fine inside a private network and not on a public host. The route reads `METRICS_TOKEN` from the validated environment and, when it is set, requires `Authorization: Bearer <token>`; with it unset the route is open, and the pull request says so in its first lines so nobody deploys it without choosing.

### What about database timings?

The histogram measures each procedure end to end, which includes its Prisma calls. For per-query numbers, Prisma 6 has a `metrics` preview feature that exposes its own counters and histograms; the pull request names the generator flag and the one call that would merge them into this registry, but leaves it out so the change stays about tRPC.

## More tRPC jobs

- [Add Protected Procedures to a tRPC API](https://getrush.ai/run/add-protected-procedures/trpc/)
- [Add Rate Limiting to a tRPC API](https://getrush.ai/run/add-rate-limiting/trpc/)
- [Add Real-Time Updates to a tRPC App](https://getrush.ai/run/add-realtime-updates/trpc/)

## The same job on other stacks

- [Add Prometheus Metrics to a Vapor App](https://getrush.ai/run/add-prometheus-metrics/vapor/)
- [Add Prometheus Metrics to an Actix Web App](https://getrush.ai/run/add-prometheus-metrics/actix/)
- [Add Prometheus Metrics to an aiohttp App](https://getrush.ai/run/add-prometheus-metrics/aiohttp/)

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