# Add CORS to a Koa App

Yes. An agent adds @koa/cors ahead of your Koa routes with an origin allowlist, credentials and preflight handling, proves it with supertest, and opens a PR.

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

## What the agent does

The agent reads how the app's middleware is assembled before it adds a layer, because CORS headers have to be set before a router answers and before an error handler replaces the response. In a repository laid out like koajs/examples, every example is a directory whose `app.js` does `const app = module.exports = new Koa()` and calls `app.listen(3000)` only when `!module.parent`, which is what lets each `test.js` mount it with `supertest.agent(app.listen())`. The root `package.json` pins `koa` at `^2.2.0`, `@koa/router` at `^8.0.5`, `koa-body` at `^4.0.8`, `koa-session` at `^5.0.0`, `koa-csrf` at `^3.0.6` and `koa-logger` at `^3.0.0`, with `mocha` `^5.0.0`, `supertest` `^3.0.0`, `should` and `eslint` `^3.8.1` under `eslint-config-koa` as dev dependencies; `npm test` is `NODE_ENV=test mocha --harmony --reporter spec --require should */test.js`, `npm run lint` is `eslint .`, `engines` asks for Node `>= 7.6`, and there is no lockfile. `.travis.yml` runs lint and tests on `stable` and `8`, and `Readme.md` lists each example with one line.

No example sets a CORS header. The `csrf` example shows the pattern the new one follows: `app.keys`, `koa-session`, `koaBody()`, `new CSRF()`, then a `@koa/router` with `/token` and `/post`, and a `test.js` that fetches a token, then posts with and without it and asserts 403 or 200. The `errors` example wraps `next()` in a `try` that sets `ctx.status` from `err.status` and emits `error` on the app, which matters because a header set before the throw survives only if the middleware keeps it. The `404` example uses `ctx.accepts` to answer HTML, JSON or text. The `body-parsing` test posts JSON and urlencoded bodies and expects 413 over `jsonLimit`.

The agent adds `@koa/cors`, whose current release is 5.0.0, and writes a `cors/` example in the same shape. Since 5.0, the middleware's default `origin` is `*`; before, it reflected the request's `Origin`, and the README shows the one-line `origin(ctx)` function that restores that. The example does neither: it reads an allowlist from `CORS_ORIGINS`, a comma-separated environment variable, and its `origin` function returns the request's `Origin` when it is in the list and nothing otherwise, so a page from an unknown site gets no `Access-Control-Allow-Origin` at all. It sets `credentials: true`, which browsers refuse to pair with `*`, `allowHeaders` to `Content-Type` and `Authorization`, `exposeHeaders` for a request id, and `keepHeadersOnError: true` so the headers are copied onto `err.header` when a later middleware throws and the `errors`-style handler still answers with them. `app.use(cors(...))` comes before `koaBody()` and before `router.routes()`, so a preflight `OPTIONS` never reaches the body parser or a route. `cors/test.js` uses `supertest` the way `csrf/test.js` does: an `OPTIONS` with `Origin` and `Access-Control-Request-Method` expects 204 with the allow-origin, allow-credentials and `Vary: Origin` headers; a `GET` from a listed origin expects the header echoed; a `GET` from an unlisted origin expects it absent; a `GET` with no `Origin` expects a plain response. `Readme.md` gains a line for `cors`.

For a reader's own app the same middleware goes in `app.js` before the router with the same options, and the agent says so in the pull request rather than inventing a second app. It runs `npm install`, which adds `@koa/cors` to `package.json`'s dependencies, then `npm test`, which picks up `cors/test.js` through the `*/test.js` glob, and `npm run lint`, where the Koa ESLint config checks semicolons and spacing in the two new files. `@koa/cors` 5.0.0 declares Node `>= 14.0.0` in its `engines`, which is newer than the repository's `>= 7.6`, so the pull request notes the floor the new dependency sets.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add CORS to this Koa repository. Read package.json, .eslintrc.yml, .travis.yml, Readme.md, csrf/app.js, csrf/test.js, errors/app.js and body-parsing/test.js first. Install @koa/cors and add a cors/ example with app.js and test.js in the same shape as csrf/: the app exports a Koa instance and listens only when run directly; cors() is mounted before koa-body and before the router; origin is a function that returns the request Origin only when it is in a CORS_ORIGINS comma-separated allowlist; credentials is true; allowHeaders covers Content-Type and Authorization; keepHeadersOnError is true. Write supertest tests for a preflight OPTIONS from a listed origin, a GET from a listed origin, a GET from an unlisted origin and a GET with no Origin header, asserting the Access-Control headers and Vary. Add the example to Readme.md. Do not change any other example. Run npm install, npm test and npm run lint, note the Node version @koa/cors requires against the engines field, and open a pull request with the test 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 `cors/app.js` and `cors/test.js`, adds `@koa/cors` to `package.json`, and adds one line to `Readme.md`. Its description shows the mocha output for the new tests beside the existing ones and the `eslint` result, and names the `engines` floor `@koa/cors` 5 brings.

The repository has no GitHub Actions workflow, only `.travis.yml`, so the run's record is the proof that `npm test` and `npm run lint` pass with the new example included; a team that has moved to Actions gets the same commands run there on the pull request.

Before merging, a reviewer decides whether the allowlist should come from an environment variable or from configuration in code, whether `credentials: true` is needed when the API uses bearer tokens rather than cookies, and whether `maxAge` should be set so browsers cache the preflight for the routes called most.

## Run it on every Koa service a browser app calls from another origin

A team with several Koa services starts one run per repository from its own server: a `POST /o/{org}/sessions` each, with this prompt as `input`, 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 `app.js`, so a service that already has a `koa-helmet` layer gets the CORS middleware placed after it, and one that answers only JSON gets `allowHeaders` tuned to what its clients send.

A team that files platform work as Linear issues runs the same prompt from an automation in the Project with a `linear` trigger on issues labelled `cors`. The trigger adds the issue after the prompt, so an issue that names the frontend origins to allow, or the header a client needs exposed, reaches the agent with those values, and the pull request links back to it.

## Why run it on Rush?

CORS mistakes are invisible in a terminal: `curl` never sends `Origin`, so a server that answers it fine can still block every browser. The agent writes the preflight and the cross-origin requests as `supertest` tests, runs them in its own sandbox with the repository's own `mocha` and `eslint`, and keeps the output with the run, so the pull request carries the proof a laptop check skips.

The same prompt runs across every Koa service at once, each in its own sandbox with its own pull request, and each reads the middleware order of its own app rather than applying one template.

## Frequently asked questions

### Why not leave origin at the default?

Since 5.0 the default is `*`, which lets any page read the response and cannot be combined with `credentials: true`, since browsers reject that pair. An allowlist function answers the listed origins by name, sets `Vary: Origin` so caches keep the answers apart, and leaves everyone else without the header.

### Why does the middleware go first?

A preflight `OPTIONS` carries no body and matches no route, so if `koa-body` or the router ran first the request would be parsed for nothing or answered 404 before the CORS headers were set. Mounted first, `@koa/cors` answers the preflight itself with 204 and adds headers to every other response on the way back.

### What changed between @koa/cors 4 and 5?

The default `origin`. Version 4 reflected the request's `Origin` header, which allowed every site while looking restrictive; version 5 sends `*`. The README shows a one-line `origin(ctx)` that restores the old behaviour, and the example replaces both with an allowlist. Version 5 also declares Node 14 or newer in its `engines`.

### Does it handle preflights for my router's routes?

Yes, because the middleware sits above the router: any `OPTIONS` with `Access-Control-Request-Method` is answered before `router.routes()` runs, whatever the path. `allowMethods` defaults to `GET,HEAD,PUT,POST,DELETE,PATCH`, which covers the verbs the examples' routers use.

### Will it work with koa-session cookies?

With `credentials: true` and a named origin, the browser sends and accepts cookies on cross-origin requests, which is what the `csrf` example's session needs. The cookie itself also has to allow it, with `SameSite=None` and `Secure` set on the session cookie, which is a `koa-session` option rather than a CORS one, and the pull request says so.

## More Koa jobs

- [Add Test Coverage to CI for a Koa API](https://getrush.ai/run/add-coverage-to-ci/koa/)
- [Add TypeORM Migrations to a Koa API](https://getrush.ai/run/add-database-migrations/koa/)
- [Add Dependabot to a Koa API](https://getrush.ai/run/add-dependabot/koa/)

## The same job on other stacks

- [Add CORS and Rate Limiting to a Ktor Server from a Linear Issue](https://getrush.ai/run/add-cors/ktor/)
- [Add CORS to a Litestar API](https://getrush.ai/run/add-cors/litestar/)
- [Add CORS to a Quarkus REST API](https://getrush.ai/run/add-cors/quarkus/)

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