# Add CORS to an Axum API

Yes. An agent adds tower-http's CorsLayer to your Axum API with origins from config, allows the Authorization header it reads, tests preflight, and opens a PR.

[Run this on Rush](https://cloud.getrush.ai/run/add-cors/axum/). 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 API authenticates before it chooses which headers a browser may send. In an API shaped like launchbadge/realworld-axum-sqlx, `Cargo.toml` pins `axum` 0.3.4, `tower` 0.4 and `tower-http` 0.2 with only the `trace` feature, `sqlx` 0.5 on Postgres and `clap` for configuration, and `src/config.rs` defines `Config` with two fields read from flags or the environment, `database_url` and `hmac_key`. In `src/http/mod.rs`, `serve` builds `api_router()` from the `users`, `profiles` and `articles` routers and wraps it in a `ServiceBuilder` with an `AddExtensionLayer` carrying the `ApiContext` and a `TraceLayer`, then binds `0.0.0.0:8080`. `src/http/extractor.rs` defines `AuthUser`, which reads `Authorization: Token <jwt>` and verifies it with the HMAC key. There is no CORS layer, so a browser frontend on another origin gets no answer to its preflight.

The agent enables the `cors` feature on `tower-http`, which that 0.2 release provides beside `trace`, and adds a `cors_allowed_origins` field to `Config` with `#[clap(long, env)]`, a comma-separated list that may be empty. In `serve` it builds a `CorsLayer` from that list: `allow_origin` with the parsed origins, `allow_methods` for `GET`, `POST`, `PUT`, `DELETE` and `OPTIONS`, `allow_headers` including `Authorization` and `Content-Type`, and no credentials, since the token travels in a header. The layer is added to the `ServiceBuilder` ahead of the trace layer so a preflight is answered before any handler and no `AuthUser` extraction runs on it. An empty list builds a layer that allows no origin, so a deployment opts in.

The test goes beside the router it exercises. A new test module in `src/http/mod.rs` builds the router with a `Config` whose `cors_allowed_origins` names one origin and drives it with `tower::ServiceExt::oneshot`, the way axum applications are tested without binding a port: an `OPTIONS /api/articles` with `Origin`, `Access-Control-Request-Method: POST` and `Access-Control-Request-Headers: authorization` from the allowed origin answers with the matching `access-control-allow-origin` and an allow-headers value that includes `authorization`; the same request from another origin gets no allow-origin header; and a `GET /api/tags` with the allowed `Origin` carries the header on its normal response. The pool in `ApiContext` comes from the same `DATABASE_URL` the workflow sets.

Before it pushes, the agent runs what `.github/workflows/rust.yml` runs: `sqlx db setup`, `cargo build --verbose`, `cargo test --verbose`, then `cargo run` in the background and the Realworld Postman collection the workflow checks out, which sends no `Origin` header and should be unaffected. It also runs `cargo fmt --check` and `cargo clippy`, and documents `CORS_ALLOWED_ORIGINS` in `README.md` beside the other two variables `Config` reads.

## Start it with one API call

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

```json
{
  "agent": "codex",
  "input": "Add CORS to this Axum API and open a pull request. Read Cargo.toml, src/main.rs, src/config.rs, src/http/mod.rs, src/http/extractor.rs, src/http/users.rs and .github/workflows/rust.yml first. Enable the cors feature on tower-http in Cargo.toml without changing its version. Add a cors_allowed_origins field to Config with #[clap(long, env)], a comma-separated list that may be empty. In serve, build a tower_http::cors::CorsLayer from that list: the parsed origins, methods GET, POST, PUT, DELETE and OPTIONS, headers including Authorization and Content-Type, no credentials, and no origin allowed when the list is empty. Add it to the ServiceBuilder before the TraceLayer. Add a test module in src/http/mod.rs that builds the router with one allowed origin and uses tower::ServiceExt::oneshot: a preflight OPTIONS /api/articles requesting POST with the authorization header from the allowed origin gets the matching access-control-allow-origin and an allow-headers value including authorization, the same from another origin gets no allow-origin header, and GET /api/tags with the allowed Origin carries the header; use the DATABASE_URL the workflow sets for the pool. Run sqlx db setup, cargo build --verbose, cargo test --verbose, cargo fmt --check and cargo clippy, then run the server and the Realworld Postman collection, paste the output in the pull request description, and document CORS_ALLOWED_ORIGINS in README.md. Do not change any route, extractor or migration.",
  "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 with the `cors` feature on `tower-http` in `Cargo.toml` and the matching `Cargo.lock` change, a third field on `Config` in `src/config.rs`, the `CorsLayer` in `serve` and a test module in `src/http/mod.rs`, and a README line. The description shows a `curl -X OPTIONS` preflight from the sandbox with the response headers for an allowed and a disallowed origin, and the build, test, fmt, clippy and Postman output from the branch.

The repository's `Rust` workflow runs on the pull request against its Postgres service container, so the new tests run under `cargo test --verbose` and the spec suite runs after them. The agent pushes one commit for the layer and config and one for the tests and README.

A reviewer checks that the layer sits ahead of the trace layer and the extension layer, that the origin list is read from the environment and empty by default, that `Authorization` is among the allowed headers because `AuthUser` reads it, and that `users`, `profiles` and `articles` are untouched. Then they set `CORS_ALLOWED_ORIGINS` to their frontend's origin in each environment.

## Run it on every new frontend origin

A team with several Rust APIs behind separate frontends starts one run per repository with `POST /o/{org}/sessions`, this prompt and the repository in `resources`. The agent reads each API's own extractor, so an API that authenticates with a cookie gets credentials allowed and an explicit origin list rather than a wildcard, and each run opens its own pull request.

The key's `webhook_url` receives `run.completed` for each run it starts, with a `session_url` for the result, so a script can post the pull request links to the team channel as they land.

## Why run it on Rush?

CORS failures show up only in a browser, and the quick fix is `Any` for every origin, which is wrong for an API that reads a bearer token. In a Rush sandbox the agent reads the extractor to learn which header the preflight must allow, sends real preflights with `curl` from allowed and disallowed origins against the running binary, and the responses are kept in the transcript beside the test output, so the pull request shows the exact headers a browser will see.

The result passes the repository's own gates, the build, the tests and the Realworld Postman collection that `rust.yml` runs, before a reviewer opens it, and the origin list is a deployment setting rather than a constant. The same request works unchanged across every Axum service the team owns.

## Frequently asked questions

### Does tower-http 0.2 have a CORS layer?

Yes. The 0.2 release lists `cors` among its feature flags beside `trace`, which this repository already enables. The agent turns the feature on in `Cargo.toml` without bumping the version, so no other dependency moves.

### Why not allow any origin?

Because the API authenticates with a token in the `Authorization` header, and a wildcard lets any site make a browser send requests that other code on that page could attach the token to. Reading `CORS_ALLOWED_ORIGINS` from the environment keeps the list explicit per deployment and empty until someone sets it.

### Why is the layer placed before the trace layer?

So a preflight is answered by the CORS layer before the request reaches any handler, and so that the trace layer still logs it. Nothing about `AuthUser` changes; preflights carry no token and never reach an extractor.

### Does it change the Postman API tests?

No. Newman sends no `Origin` header, so the layer adds nothing to those responses and the collection passes as before. The agent runs it in the sandbox the way the workflow does and pastes the summary.

## More Axum jobs

- [Add Code Coverage to CI for an Axum API](https://getrush.ai/run/add-coverage-to-ci/axum/)
- [Add Cursor Pagination to an Axum API](https://getrush.ai/run/add-cursor-pagination/axum/)
- [Add Full-Text Search to an Axum API](https://getrush.ai/run/add-full-text-search/axum/)

## The same job on other stacks

- [Add CORS to a Cloudflare Worker API](https://getrush.ai/run/add-cors/cloudflare-workers/)
- [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/)

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