# Add CORS to a tRPC API

Yes. An agent wraps a tRPC Next.js API route with an origin allowlist from the environment, answers preflights, tests both with Playwright, and opens a PR.

[Run this on Rush](https://cloud.getrush.ai/run/add-cors/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 route before deciding where CORS belongs. In an app laid out like trpc/examples-next-prisma-starter, the only API entry is `src/pages/api/trpc/[trpc].ts`, which exports the result of `createNextApiHandler` with `appRouter`, `createContext` and an `onError`; a `responseMeta` option sits commented out below it. `src/utils/trpc.ts` builds the browser client with `httpBatchStreamLink` pointed at `${getBaseUrl()}/api/trpc`, where `getBaseUrl()` returns an empty string in the browser, so today every caller is same-origin and no CORS header exists. `src/server/env.ts` validates `DATABASE_URL` and `NODE_ENV` with zod and is imported by `next.config.ts`, so a new variable belongs there. `playwright.config.ts` starts the app with `npm run start` in CI on port 3000, and `.github/workflows/main.yml` runs `pnpm build` then `pnpm test-e2e` with `NODE_ENV: test` against a Postgres service.

The wrapper goes around the existing handler, because `responseMeta` can add headers to a tRPC answer but cannot answer an `OPTIONS` preflight, and the browser sends one for every mutation since the client posts `application/json`. The agent adds `CORS_ALLOWED_ORIGINS` to the zod schema as an optional comma-separated string and writes `src/server/cors.ts` with one function: given the request's `Origin`, it sets `Access-Control-Allow-Origin` to that exact origin only when it is in the list, always adds `Vary: Origin`, and on a preflight copies `Access-Control-Request-Headers` back as `Access-Control-Allow-Headers`, lists `GET, POST, OPTIONS` as methods, sets a `Max-Age` so the browser caches the preflight, and ends the response with 204 before tRPC sees it. `Access-Control-Allow-Credentials` is set only when the list is explicit, never with a wildcard, so a cookie session can cross origins only to named sites.

`[trpc].ts` becomes a default export that calls the CORS function and then the handler tRPC created, so `createContext`, `onError` and the router are untouched and the batch and stream behaviour stay as they were. With the variable unset the function sets no header at all, which is today's behaviour, so a deployment that never configures it changes nothing. The README's deployment section gets the variable with an example value.

The proof is a Playwright file beside `playwright/smoke.test.ts`, because the behaviour depends on Next's real routing of `OPTIONS` to the page handler. `playwright/cors.test.ts` uses the `request` fixture to send an `OPTIONS` to `/api/trpc/healthcheck` with `Origin: https://app.example` and `Access-Control-Request-Method: POST` and asserts 204 with the allow headers, sends a `GET` from the same origin and asserts the body still answers `yay!` with the origin header set, and sends one from `https://evil.example` and asserts no `Access-Control-Allow-Origin` is present. The workflow's e2e job gets `CORS_ALLOWED_ORIGINS: https://app.example` in its `env` so the test has a list to check against; `pnpm lint` and `pnpm typecheck` run clean.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add CORS to this tRPC API for browser clients on other origins. Read src/pages/api/trpc/[trpc].ts, src/utils/trpc.ts, src/server/env.ts, next.config.ts, playwright.config.ts, playwright/smoke.test.ts, package.json and .github/workflows/main.yml first. Add CORS_ALLOWED_ORIGINS to the zod env schema as an optional comma-separated string. Write src/server/cors.ts that, for a request whose Origin is in the list, sets Access-Control-Allow-Origin to that origin and Vary: Origin, sets Allow-Credentials only when the list is explicit, and for an OPTIONS preflight echoes Access-Control-Request-Headers, allows GET, POST and OPTIONS, sets Max-Age and ends with 204. Wrap the handler in [trpc].ts so the preflight never reaches tRPC and an unset variable changes nothing. Add playwright/cors.test.ts covering the preflight, an allowed GET and a refused origin, set CORS_ALLOWED_ORIGINS in the e2e job's env, document the variable in README.md, run pnpm lint, pnpm typecheck and pnpm test-e2e, and open a pull request with the output.",
  "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 adds `src/server/cors.ts` and `playwright/cors.test.ts`, changes `src/pages/api/trpc/[trpc].ts`, `src/server/env.ts`, `README.md` and `.github/workflows/main.yml`. Its description pastes the lint, typecheck and Playwright output, including the three response header sets, so a reviewer sees exactly what a browser on an allowed and on a refused origin receives.

A separate front end, a browser extension or a staging site listed in `CORS_ALLOWED_ORIGINS` can now call every procedure, with the preflight cached for `Max-Age` so each mutation costs one request after the first. An origin not on the list gets the tRPC answer with no allow header, which the browser refuses to hand to the page, and the server-side callers in `post.test.ts` are unaffected because they never go through HTTP.

Before merging, a reviewer sets the production list, decides whether credentials should cross origins at all, and checks that the proxy in front of the app does not strip `Vary`, without which a CDN could serve one origin's allow header to another.

## Run it on every front end deployed on its own domain

A team whose tRPC APIs each gain a separate client app starts one run per repository from the terminal: one `POST /o/{org}/sessions` each with that repository in `resources` and a `request_id` that is a UUID v5 of its full name, so a retried call returns the run already started. Each run reads its own adapter: an app on the fetch adapter or the App Router gets the same function on `Request` and `Response` objects, an Express or Fastify host gets the framework's CORS plugin configured from the same variable, and one that already answers preflights gets only the allowlist and the tests.

Each run opens its own pull request on its own branch, and `GET /o/{org}/sessions` lists them newest first, so the person who started the batch reads every Playwright result from one place.

## Why run it on Rush?

CORS is checked by the browser, not the server, so a change that looks right in a unit test can still fail in a tab: an `OPTIONS` that reaches tRPC and answers 405, a wildcard paired with credentials that every browser rejects, or a missing `Vary` that a cache turns into a leak. The agent tests against the built Next app with real HTTP in its sandbox, and the assertions stay in the e2e suite CI already runs.

The run keeps every command and its output, so the reviewer reads the three header sets without building the app or starting Postgres locally. Several APIs can be opened to their clients at once, each in its own sandbox, and one that already handles preflights is left with a note rather than a second wrapper.

## Frequently asked questions

### Why not use responseMeta?

`responseMeta` runs after tRPC has handled a call and can add headers to that answer, but a preflight is an `OPTIONS` request with no procedure, which tRPC does not handle. The wrapper answers the preflight itself and hands everything else to the handler tRPC made, so the existing options keep working.

### Does a wildcard work?

The agent supports `*` in the list for a public read-only API, and in that case never sets `Access-Control-Allow-Credentials`, because browsers reject the pair. For an app with a session cookie the list must name origins, and the pull request says so beside the variable.

### Will the Playwright test run locally?

Yes, with `CORS_ALLOWED_ORIGINS=https://app.example pnpm test-e2e`, which `playwright.config.ts` runs against `npm run dev` outside CI. Without the variable the two allowed-origin assertions fail by design, since the API is then same-origin only.

### Does this change the batch or stream links?

No. The wrapper reads the `Origin` header and the method and otherwise passes the request through, so `httpBatchStreamLink` batches and streams exactly as before. The only visible difference for a same-origin browser is nothing: it sends no `Origin` that the list matches, and receives no new header.

## More tRPC jobs

- [Add Vitest Coverage to CI for a tRPC and Prisma App](https://getrush.ai/run/add-coverage-to-ci/trpc/)
- [Add Cursor Pagination to a tRPC Router](https://getrush.ai/run/add-cursor-pagination/trpc/)
- [Add a Dockerfile to a tRPC Next.js App](https://getrush.ai/run/add-dockerfile/trpc/)

## The same job on other stacks

- [Add CORS to a Vapor Server](https://getrush.ai/run/add-cors/vapor/)
- [Add CORS to an Actix Web API](https://getrush.ai/run/add-cors/actix/)
- [Add CORS to an aiohttp App](https://getrush.ai/run/add-cors/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/)
