# Add CORS to an Actix Web API

Yes. An agent adds actix-cors to your Actix Web API with an allowed-origin list from the environment, tests the preflight with init_service and opens a PR.

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

## What the agent does

The agent reads the service before touching middleware. In an API shaped like the `basics/nested-routing` member of actix/examples, the workspace `Cargo.toml` sets `edition = "2024"`, `rust-version = "1.98"`, `actix-web = "4.11"` and `actix-cors = "0.7"`, and the crate's own `Cargo.toml` takes `actix-web`, `env_logger`, `log` and `serde` from the workspace. `src/main.rs` builds `App::new().configure(config_app).wrap(middleware::Logger::default())` and binds `127.0.0.1:8080`. `src/app_config.rs` nests a `/products` scope with `GET` and `POST` on the collection, `GET` and `DELETE` on `/{product_id}`, and a `/parts` scope beneath it with the same shape; the handlers in `src/handlers/products.rs` and `parts.rs` take `web::Json<Product>`, `web::Query` and `web::Path<String>` and answer `200`. There is no CORS layer, so a browser frontend on another origin cannot call `POST /products`.

The same repository shows the pattern to follow in `cors/backend/src/main.rs`: `Cors::default().allowed_origin("http://localhost:8081").allowed_methods(vec!["GET", "POST"]).allowed_headers(vec![header::AUTHORIZATION, header::ACCEPT]).allowed_header(header::CONTENT_TYPE).supports_credentials().max_age(3600)`, wrapped around the whole `App`. The agent adds `actix-cors.workspace = true` to the crate's `Cargo.toml`, and builds the middleware in `main.rs` from an `ALLOWED_ORIGINS` environment variable, comma-separated, read once at startup: one `allowed_origin` call per entry, `allowed_methods` of `GET`, `POST`, `DELETE` and `OPTIONS` to match `app_config.rs`, `allowed_headers` of `Content-Type` and `Authorization`, and a `max_age`. An empty variable allows no origin. It does not call `allow_any_origin`, and it leaves `supports_credentials` off because the API has no cookies.

Order matters in Actix: middleware registered last runs first, so `.wrap(Cors)` goes after `.wrap(Logger)` in the builder, which makes CORS the outer layer and lets the preflight `OPTIONS` be answered before routing, while the logger still records it. The agent notes that in the pull request because it is the usual mistake.

Tests follow the one already in `src/handlers/products.rs`, which calls `test::init_service(App::new().configure(config_app))` and posts a JSON payload. The agent moves the CORS construction into a function in `src/app_config.rs` so tests can wrap the same middleware, and adds `#[actix_web::test]` cases: an `OPTIONS /products` with `Origin` and `Access-Control-Request-Method: POST` from an allowed origin answers with a matching `Access-Control-Allow-Origin` and the allowed headers; the same preflight from another origin carries no allow-origin header; a `GET /products` with an allowed `Origin` carries the header on its `200`; and a request with no `Origin` is unchanged. It runs `cargo test -p nested-routing` and `cargo clippy -p nested-routing --all-targets` in the sandbox, the checks `.github/workflows/ci.yml` and `clippy-fmt.yml` run on the workspace, and pastes both.

## Start it with one API call

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

```json
{
  "agent": "codex",
  "input": "Add CORS to this Actix Web API and open a pull request. Read the workspace Cargo.toml, the crate's Cargo.toml, src/main.rs, src/app_config.rs and the handlers and their tests first. Use the actix-cors crate the workspace already pins; add it to the crate's dependencies as a workspace dependency. Build the Cors middleware from a comma-separated ALLOWED_ORIGINS environment variable read at startup, one allowed_origin per entry, with allowed_methods GET, POST, DELETE and OPTIONS, allowed_headers Content-Type and Authorization, and a max_age; an empty variable must allow no origin, and do not use allow_any_origin or supports_credentials. Register it so it is the outermost middleware. Put the construction in a function the tests can call, and add #[actix_web::test] cases beside the existing one: a preflight OPTIONS /products from an allowed origin answers with the matching allow-origin and allow-headers, the same from another origin has no allow-origin header, GET /products from an allowed origin carries the header on its 200, and a request without Origin is unchanged. Run cargo test and cargo clippy --all-targets for this crate and paste the output. Do not change the routes or the bind address.",
  "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 one dependency line in the crate's `Cargo.toml`, a `cors()` function in `src/app_config.rs` that reads `ALLOWED_ORIGINS`, a `.wrap(cors())` in `src/main.rs` placed to run outermost, and four new test cases next to the existing `test_add_product`. The description shows the preflight response headers from a test and the `cargo test` and `cargo clippy` output from the sandbox.

In the examples workspace the `ci.yml` workflow runs `cargo check` and `cargo test --workspace` and `clippy-fmt.yml` runs Clippy and rustfmt on pull requests, so the new cases run as checks. On a standalone API the team's own workflow does the same, or the pasted output is the check.

A reviewer checks that the middleware is outermost, that an empty `ALLOWED_ORIGINS` allows nothing rather than everything, that `DELETE` is in the allowed methods because `app_config.rs` routes it, and that `Authorization` is allowed only if the frontend will send one. Then they set `ALLOWED_ORIGINS` per environment where the service runs.

## Run it on every new frontend origin

A team with several Actix services behind separate frontends sends one `POST /o/{org}/sessions` per repository with this prompt and that repository in `resources`. Each run reads its own `App` builder and routes, so a service that already wraps `Cors::permissive()` gets the explicit list instead, and each opens its own pull request. One repository per run; a `request_id` in the body makes a retry safe.

Give the API key a `webhook_url` and Rush POSTs `run.completed` when each turn ends, with the `session_url` to read the pull request from, so the origin list in each service can be checked against the frontend that calls it.

## Why run it on Rush?

CORS failures only show up in a browser, and the quick fix found in a search is `Cors::permissive()`, which allows any origin with credentials. In a Rush sandbox the agent sends real preflights through `init_service` with `Origin` and `Access-Control-Request-Method` set, from an allowed and a disallowed origin, and the response headers are kept in the run's record beside the test output, so the pull request shows what a browser will see.

The change is a dozen lines, but the proof is the work: the middleware order, the environment parsing, the four cases and a Clippy pass on the 2024 edition. The agent does it in one pass, runs the workspace's own checks before pushing, and the same request works unchanged on the next Actix service.

## Frequently asked questions

### Why not Cors::permissive()?

Because it allows any origin, any method and any header, with credentials, which is fine for a local demo and wrong for an API that accepts `POST` and `DELETE`. Reading `ALLOWED_ORIGINS` from the environment keeps the list explicit per deployment and empty until someone sets it.

### Does it add a dependency?

In the examples workspace, `actix-cors = "0.7"` is already in `[workspace.dependencies]`, so the crate only gains `actix-cors.workspace = true`. In a standalone API the agent adds `actix-cors` at its current 0.7 release and the `Cargo.lock` line that comes with it.

### Why does the middleware order matter?

Actix runs `wrap` calls in reverse registration order, so the last `.wrap` is the outermost. CORS must be outermost to answer `OPTIONS` preflights before routing rejects them and to add headers to error responses. The agent registers it last and says so in the pull request.

### What about credentials and cookies?

The API in the example has no cookie sessions, so `supports_credentials` stays off and no origin can send cookies cross-site. If your frontend needs them, the allowed origins must stay an explicit list, because browsers refuse credentials with a wildcard; the pull request notes this but does not turn it on.

## More Actix Web jobs

- [Add CSRF Protection to an Actix Web App](https://getrush.ai/run/add-csrf-protection/actix/)
- [Add Cursor Pagination to an Actix Web API](https://getrush.ai/run/add-cursor-pagination/actix/)
- [Add Database Migrations to an Actix Web App](https://getrush.ai/run/add-database-migrations/actix/)

## The same job on other stacks

- [Add CORS to an aiohttp App](https://getrush.ai/run/add-cors/aiohttp/)
- [Add CORS to an Axum API](https://getrush.ai/run/add-cors/axum/)
- [Add CORS to a Cloudflare Worker API](https://getrush.ai/run/add-cors/cloudflare-workers/)

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