# Add CORS to a Cloudflare Worker API

Yes. An agent adds origin-checked CORS with preflight handling to a Worker's JSON API, exposes its custom header, tests it with Vitest, and opens a pull request.

[Run this on Rush](https://cloud.getrush.ai/run/add-cors/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 header. In a project like the `d1-starter-sessions-api-template` in cloudflare/templates, `package.json` runs `wrangler dev`, `vitest` and a `check` script of `tsc && wrangler deploy --dry-run`, with `wrangler` 4.136.1, `vitest` 4.1.10, `@cloudflare/vitest-pool-workers` 0.21.3 and `durable-utils` as dev dependencies. `wrangler.jsonc` sets a `compatibility_date` of 2025-10-08, serves `public/` as static assets, binds a D1 database as `DB01`, and turns on observability and source map upload. `vitest.config.mts` runs the tests inside `workerd` through `cloudflareTest` with that config, and `test/index.spec.ts` already calls `worker.fetch` with `env` from `cloudflare:test` to list orders and create one.

`src/index.ts` is a single `fetch` handler. It reads an `x-d1-bookmark` request header, opens a D1 session with it, dispatches `GET /api/orders`, `POST /api/orders` and `POST /api/reset` with `Retries.tryWhile` around each query, answers anything else with a plain `404`, sets `x-d1-bookmark` on every successful response so the client can continue the session, and answers a thrown error with a `500` JSON body. The `Env` type is declared by hand as `{ DB01: D1Database }`. No response carries an `Access-Control-*` header, and there is no handling of `OPTIONS`, so a page on another origin cannot call the API, and even a same-origin page cannot read `x-d1-bookmark` from JavaScript when the call crosses origins, because custom headers are hidden unless exposed. The bundled `public/index.html` works only because it is served from the same Worker.

The agent adds `src/cors.ts` with two functions. `corsHeaders(origin, allowed)` returns the headers for a matched origin: `Access-Control-Allow-Origin` echoing that origin, `Vary: Origin` so caches keep responses apart, `Access-Control-Allow-Methods` of `GET, POST, OPTIONS`, `Access-Control-Allow-Headers` of `Content-Type` and `x-d1-bookmark`, `Access-Control-Expose-Headers` of `x-d1-bookmark`, and an `Access-Control-Max-Age`; an unmatched origin gets no CORS headers at all. `isAllowed(origin, list)` compares exact origins from a comma-separated `ALLOWED_ORIGINS` var that the agent adds under `vars` in `wrangler.jsonc` and to the `Env` type, then regenerates `worker-configuration.d.ts` with `wrangler types`. In `index.ts`, an `OPTIONS` request under `/api/` answers `204` with those headers before any session is opened, and every `/api/` response, including the `500` error body, is returned through a `withCors` wrapper that copies the response and appends the headers, so the bookmark header and the allow headers travel together. The static assets and the `404` are untouched.

Tests sit beside the existing ones in `test/index.spec.ts`, which run inside `workerd` with the real `env`. A preflight `OPTIONS /api/orders` from an allowed origin answers `204` with the matching allow-origin, the allowed methods and headers, and `Vary: Origin`; the same preflight from another origin answers without any `Access-Control-Allow-Origin`; `GET /api/orders` with an allowed `Origin` carries the allow-origin and the expose header beside `x-d1-bookmark`; and a request with no `Origin` behaves as before. The agent sets `ALLOWED_ORIGINS` for the tests through the Vitest pool's `miniflare.bindings`, runs `npm test` and `npm run check`, starts `wrangler dev` and sends a preflight with `curl -X OPTIONS` to read the headers back, and pastes both outputs in the pull request.

## Start it with one API call

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

```json
{
  "agent": "codex",
  "input": "Add CORS to the /api routes of this Cloudflare Worker and open a pull request. Read package.json, wrangler.jsonc, tsconfig.json, vitest.config.mts, worker-configuration.d.ts, src/index.ts, test/index.spec.ts, test/tsconfig.json, public/index.html and README.md first. Add an ALLOWED_ORIGINS var under vars in wrangler.jsonc holding a comma-separated list of exact origins, add it to the Env type and regenerate worker-configuration.d.ts with wrangler types. Write src/cors.ts with an isAllowed check and a corsHeaders function that returns Access-Control-Allow-Origin echoing the matched origin, Vary Origin, allowed methods GET POST OPTIONS, allowed headers Content-Type and x-d1-bookmark, exposed header x-d1-bookmark and a max age, and nothing for an unmatched origin. Answer OPTIONS under /api/ with 204 and those headers before opening a D1 session, and append the headers to every /api/ response including the 500 error body, leaving static assets and the 404 alone. Add tests in test/index.spec.ts for the preflight from an allowed and from another origin, a GET with an allowed Origin that carries the expose header beside x-d1-bookmark, and a request with no Origin; set ALLOWED_ORIGINS for the tests through the Vitest pool's miniflare bindings. Run npm test and npm run check, start wrangler dev and send a preflight with curl, and paste both in the pull request. Document the var in README.md. Do not add a dependency and do not change the compatibility_date or the D1 binding.",
  "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. The diff adds `src/cors.ts`, changes `src/index.ts`, `wrangler.jsonc`, `worker-configuration.d.ts`, `vitest.config.mts`, `test/index.spec.ts` and `README.md`, and leaves `package.json` and `package-lock.json` untouched, which a reviewer can confirm from the file list. The description names the var, shows the `curl -X OPTIONS` call with the headers that came back from `wrangler dev`, and pastes the Vitest output with each case named and the `tsc` and dry-run deploy from `npm run check`.

The run's full record at `GET /o/{org}/sessions/{id}/messages` keeps the test run inside `workerd`, the type generation, the `wrangler dev` start and the preflight request. `GET /o/{org}/p/{project}/sessions/{id}/changes` returns each file's diff. The repository's own `check` scripts run on a pull request, and the template linter sees no new dependency.

Before merging, a reviewer checks that the origin match is exact rather than a prefix, that `Vary: Origin` is present wherever `Access-Control-Allow-Origin` is, that the expose header names `x-d1-bookmark` so cross-origin clients can continue a session, and that the preflight answers before any database work. Nothing is deployed; the `deploy` script is never run.

## Run it on every new frontend origin

When a new web client is created for the API, a step in that client's setup sends `POST /o/{org}/sessions` with this prompt, the origin to add named in the text, and the Worker's repository in `resources`. The agent reads the current `ALLOWED_ORIGINS` list, adds the origin, extends the tests with the new value and opens a pull request, one per origin, each on its own branch.

Give the API key a `webhook_url` and Rush POSTs `run.completed` when the turn ends, with `session_url` to read the pull request from. A `request_id` that is a UUID v5 of the origin returns the run already started if the setup step is repeated.

## Why run it on Rush?

CORS mistakes are invisible until a browser on another origin tries the call: a missing `Vary`, a preflight that opens a database session first, a custom header the client cannot read because it was never exposed. The agent runs the Worker's tests inside `workerd` and a real `wrangler dev` in its own sandbox, sends the preflight itself and reads the headers back before it pushes.

The pull request carries the preflight response, the test names and the diff, and the trajectory keeps every command, so a reviewer who has not run the Worker can still see which origins are allowed and which headers a client will be able to read.

## Frequently asked questions

### Why not allow every origin?

The API writes orders, and an `Access-Control-Allow-Origin: *` would let any page call it from a visitor's browser. An exact list in `ALLOWED_ORIGINS` is the safe default, and adding an origin is a one-line var change with a test. If a route is meant to be public and read-only, say so in the prompt and the agent allows `*` on that route only.

### Why expose x-d1-bookmark?

The Worker returns the D1 session bookmark in that header so the next request can continue the session and see its own writes. Browsers hide custom response headers from cross-origin JavaScript unless `Access-Control-Expose-Headers` names them, so without that line a cross-origin client would silently lose read-after-write consistency.

### Does the preflight hit the database?

No. The `OPTIONS` branch answers `204` with the CORS headers before `env.DB01.withSession` is called, so preflights cost no D1 query and cannot fail on a database error. The `Access-Control-Max-Age` lets the browser cache the answer so repeated calls skip the preflight.

### How are the tests given an allowed origin?

Through the Vitest pool's `miniflare.bindings` in `vitest.config.mts`, which sets `ALLOWED_ORIGINS` for the test Worker without touching the value in `wrangler.jsonc`. The tests read it from `env` the same way the handler does, so the match logic is exercised against a real list.

## More Cloudflare Workers jobs

- [Add a Cron Trigger to a Cloudflare Worker](https://getrush.ai/run/add-cron-trigger/cloudflare-workers/)
- [Add Cursor Pagination to a Cloudflare Worker on D1](https://getrush.ai/run/add-cursor-pagination/cloudflare-workers/)
- [Add D1 Migrations to a Cloudflare Worker](https://getrush.ai/run/add-d1-migrations/cloudflare-workers/)

## The same job on other stacks

- [Add CORS to a CodeIgniter 4 API](https://getrush.ai/run/add-cors/codeigniter/)
- [Add CORS to a Fiber API](https://getrush.ai/run/add-cors/fiber/)
- [Add CORS to a Flask API](https://getrush.ai/run/add-cors/flask/)

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