# Add Protected Procedures to a tRPC API

Yes. An agent adds an auth middleware and a protectedProcedure to your tRPC router, puts a user on the context, guards a mutation, tests both paths, and opens a PR.

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

## What the agent does

The agent reads the router setup before adding a middleware to it. In an app laid out like trpc/examples-next-prisma-starter, `src/server/trpc.ts` calls `initTRPC.context<Context>().create({ transformer, errorFormatter })` once and exports `router`, `publicProcedure`, `mergeRouters` and `createCallerFactory`, with a comment pointing at the docs for protected base procedures but none defined. `src/server/context.ts` has `createContextInner(_opts)` returning an empty object, a commented-out `session: Session | null` field in its options interface, and `createContext(opts: trpcNext.CreateNextContextOptions)` that ignores the request. `src/server/routers/_app.ts` mounts a `healthcheck` query and `postRouter`; `src/server/routers/post.ts` has `list`, `byId` and `add`, all on `publicProcedure`. `src/pages/api/trpc/[trpc].ts` wires `createNextApiHandler` with `createContext` and an `onError` hook. `src/server/routers/post.test.ts` builds a caller with `createCaller(await createContextInner({}))`, and `playwright/smoke.test.ts` adds a post through the form on `/`. `src/server/env.ts` validates `DATABASE_URL` and `NODE_ENV` with zod and throws on anything missing.

tRPC's mechanism is `procedure.use()`. A middleware receives `opts` with the current `ctx` and must return `opts.next()`; calling `opts.next({ ctx: { user } })` after a null check narrows the context type, so every procedure built on that base sees a non-nullable `user` without a cast. Throwing `new TRPCError({ code: 'UNAUTHORIZED' })` ends the call with the standard error shape the client already understands. The agent writes an `isAuthed` middleware in `trpc.ts` and exports `protectedProcedure = publicProcedure.use(isAuthed)` beside `publicProcedure`, which is the shape the existing comment anticipates.

Identity has to come from somewhere, and this starter has no session library, so the agent keeps the first version small and explicit. `createContextInner` takes `{ user: { id: string } | null }` and returns it, which also makes the test file's empty call a type error that the agent fixes to pass `{ user: null }`. `createContext` reads the request's `Authorization` header, compares a bearer token against a new `API_TOKEN` entry in `env.ts` with constant-time comparison, and sets `user` to `{ id: 'api' }` or `null`; `.env` gets a development value and `main.yml` gets the same variable in its `env` block, because the zod schema refuses to start without it. The comment in `context.ts` is replaced with a note on where a session lookup would go. Then the guard: `post.add` stays public so the page and the smoke test keep working, and the agent adds `post.remove`, a `protectedProcedure` mutation that deletes by id and returns the deleted row's id, as the first protected call.

Tests cover both paths through the caller, which needs no HTTP: one test builds `createCaller({ user: null })` and asserts `post.remove` rejects with a `TRPCError` whose `code` is `UNAUTHORIZED`; another builds the caller with a user, adds a post, removes it and asserts `byId` then throws `NOT_FOUND`. A third test in `context.test.ts` calls `createContext` with a mocked request carrying the right and wrong header. The agent runs `pnpm install`, `pnpm prebuild` against a Postgres it starts in the sandbox, `pnpm test-unit`, `pnpm tsc` and `pnpm test-e2e`, and reads `src/utils/trpc.ts` to confirm the `headers()` function in `httpBatchStreamLink` is where a browser client would attach a token later, without changing it now.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add protected procedures to this tRPC API. Read src/server/trpc.ts, src/server/context.ts, src/server/env.ts, src/server/routers/_app.ts, src/server/routers/post.ts, src/server/routers/post.test.ts, src/pages/api/trpc/[trpc].ts, src/utils/trpc.ts, playwright/smoke.test.ts, .env and .github/workflows/main.yml first. In trpc.ts add an isAuthed middleware that throws TRPCError UNAUTHORIZED when ctx.user is null and otherwise calls next with the narrowed user, and export protectedProcedure = publicProcedure.use(isAuthed). Make createContextInner take and return { user: { id: string } | null }, and have createContext set it from a bearer token in the Authorization header compared in constant time against a new API_TOKEN variable added to env.ts, .env and the CI workflow's env block. Keep post.add public; add post.remove as a protectedProcedure that deletes a post by id. Update post.test.ts for the new context shape and add tests that remove rejects with UNAUTHORIZED without a user and succeeds with one, plus a test for createContext with a right and a wrong header. Start Postgres, run pnpm install, pnpm prebuild, pnpm test-unit, pnpm tsc and pnpm test-e2e, and open a pull request that quotes the output and says where a session lookup would replace the token check.",
  "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/trpc.ts` (the middleware and `protectedProcedure`), `src/server/context.ts` (the context shape and the header check), `src/server/env.ts` (one variable), `.env` and `.github/workflows/main.yml` (the same variable), `src/server/routers/post.ts` (one new mutation), `src/server/routers/post.test.ts` (updated and extended) and a new `src/server/context.test.ts`. Its description quotes the Vitest, `tsc` and Playwright output from the sandbox and has a short section on swapping the token check for a session lookup.

A reviewer checks that the comparison is constant-time, that `API_TOKEN` is required by the schema so a deploy without it fails at start rather than at the first call, that `post.add` is still public so the page works, and that the `UNAUTHORIZED` test asserts on the error code rather than the message. They may ask for `post.add` to be protected too, which is a one-word change once the browser client sends a token.

After merge, any new mutation built on `protectedProcedure` carries a typed `user` and refuses unauthenticated callers with a standard tRPC error, and the pattern is in place for a session-based context when the app grows one.

## Run it on every pull request that adds a procedure

An automation on the Project with a `github` trigger on `pull_request.opened` and `pull_request.synchronize` reads the diff under `src/server/routers/` for a new `mutation` built on `publicProcedure`. An automation's run is read-only, so it posts a review comment naming each one and asking whether it should be `protectedProcedure`, with the file and line, and leaves the decision to the author.

A company with several tRPC services starts one run per repository from a handler on its own server, sending this body to `POST /o/{org}/sessions` with the repository in `resources` and a `request_id` that is a UUID v5 of the repository name, so a retried loop returns the run it already started. Each run reads its own `context.ts`; a service that already has a session on the context gets the middleware wired to it instead of a token check.

## Why run it on Rush?

Auth middleware is a small change with a large blast radius: a wrong context type breaks every procedure's inference, and a missing environment variable breaks the app at start. The agent runs the type check, the unit tests and the browser test in its own sandbox with a real database and keeps the output with the pull request, so the reviewer sees all three pass before reading the diff.

Every tRPC codebase puts identity on the context differently. An agent that reads `context.ts` and the commented-out session field writes the version that fits this starter and says in the pull request exactly where a session would replace it, instead of importing an auth library the project does not have.

## Frequently asked questions

### Why a bearer token instead of a session library?

The starter has no session library and `env.ts` already validates configuration with zod, so a required `API_TOKEN` is the smallest honest identity source. The middleware and `protectedProcedure` do not care where `user` comes from; the pull request marks the line in `createContext` where a session lookup replaces the header check.

### Does this break the existing page or tests?

No. `post.add` stays public, so the form on `/` and the Playwright smoke test keep passing. The only existing test change is passing `{ user: null }` to `createContextInner`, which the new context type requires.

### How does the context type narrow?

The middleware calls `opts.next({ ctx: { user } })` after checking `user` is not null, and tRPC merges that into the downstream context type. A procedure built on `protectedProcedure` sees `ctx.user` as non-nullable, so there is no cast and no runtime check inside the handler.

### Why does CI need a new variable?

Because `env.ts` throws when `API_TOKEN` is missing, and `main.yml` runs `pnpm build` and the tests. The agent adds the variable to the workflow's `env` block next to the existing ones so the build in CI starts the same way the sandbox did.

## More tRPC jobs

- [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/)
- [Add Request ID Logging to a tRPC API](https://getrush.ai/run/add-request-id-logging/trpc/)

## More jobs like this: Hand off a long task

- [Add publint and Are the Types Wrong Checks to a TypeScript Library](https://getrush.ai/run/add-publint-to-ci/typescript-library/)
- [Add PWA Support to an Angular App](https://getrush.ai/run/add-pwa-support/angular/)
- [Add PWA Support to an Astro Site](https://getrush.ai/run/add-pwa-support/astro/)

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