# Add CORS to a Litestar API

Yes. An agent adds a CORSConfig to your Litestar app with origins from an environment variable, tests for the headers and the preflight, and opens a PR.

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

## What the agent does

The agent reads the app and the tooling around it first, because in a repository like litestar-org/litestar-hello-world the tooling is most of the work. `app.py` builds `Litestar(route_handlers=[sync_hello_world, async_hello_world])` with two `GET` handlers, `/sync` with `sync_to_thread=False` and `/async` that sleeps briefly, and declares `__all__` as a tuple because the `ensure-dunder-all` pre-commit hook requires one. There is no `cors_config`. `tests/test_app.py` has two `TestClient` tests. `pyproject.toml` manages the project with PDM, depends on `litestar[standard]>=2.4.1`, supports Python 3.8 through 3.12, and defines a `lint` script that runs `pre-commit run --all-files` and a `test` script that runs `pytest`; Ruff is on `select = ["ALL"]` with a short ignore list at a line length of 120, and `mypy` is `strict`. `.pre-commit-config.yaml` runs Ruff, `mypy` with `litestar[standard]` as an additional dependency, `codespell`, `slotscheck`, `prettier` and the PDM lock check. `.github/workflows/ci.yaml` runs the pre-commit job and the reusable `test.yaml` on a matrix from 3.8 to 3.11 with coverage on 3.11, and `README.md` documents `pdm install` and `litestar run --reload`.

The change is small and shaped by those constraints. `app.py` gains `create_app(allowed_origins: list[str] | None = None) -> Litestar`, which builds `CORSConfig` from `litestar.config.cors` with `allow_origins` set to the argument or, when it is `None`, to the comma-separated `ALLOWED_ORIGINS` environment variable split and stripped, `allow_methods=["GET"]` because the app has only `GET` handlers, `allow_credentials=False`, and `max_age` left at its default. `app = create_app()` stays at module level so `litestar run` keeps finding it. With `from __future__ import annotations` already at the top of the file, the `list[str] | None` annotation is fine on 3.8, and the `__all__` tuple grows by `create_app`. An empty variable means an empty origin list, which is the same behaviour as today: no CORS headers at all.

Tests go in `tests/test_cors.py` and use the factory rather than the module-level app. One builds the app with a single origin and sends `GET /sync` with an `Origin` header for it, asserting `access-control-allow-origin` echoes that origin; one sends an origin that is not allowed and asserts the header is absent; one sends a preflight `OPTIONS /sync` with `Origin` and `Access-Control-Request-Method: GET` and asserts the response carries `access-control-allow-methods` and `access-control-max-age`, which the middleware Litestar installs for a `cors_config` answers without a handler of the app's own; and one uses `monkeypatch.setenv` to prove the environment variable path. The tests carry the type hints and docstrings Ruff's full rule set demands, with the `tests/**` per-file ignores the project already has.

The agent runs `pdm install`, `pdm run test` and `pdm run lint` in its sandbox, which means Ruff, `mypy --strict`, `codespell`, `slotscheck` and the `__all__` check all pass on the new code, then `litestar run` once with `ALLOWED_ORIGINS` set to confirm the headers with `curl`. `README.md` gets a line documenting the variable.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add CORS to this Litestar app. Read app.py, tests/test_app.py, pyproject.toml, .pre-commit-config.yaml, .github/workflows/ci.yaml and README.md first. Add a create_app factory in app.py that builds a CORSConfig from litestar.config.cors with allow_origins taken from its argument or, when none is given, from a comma-separated ALLOWED_ORIGINS environment variable, allow_methods GET only since the app has only GET handlers, allow_credentials False and the default max_age; keep the module-level app so litestar run still works, and add create_app to __all__ because the ensure-dunder-all hook requires it. Write tests/test_cors.py with TestClient: an allowed origin echoed in access-control-allow-origin, a disallowed origin with no header, a preflight OPTIONS with Access-Control-Request-Method GET that returns allow-methods and max-age, and the environment variable path with monkeypatch. Keep Python 3.8 compatible. Run pdm install, pdm run test and pdm run lint until Ruff, mypy, codespell and slotscheck pass, document ALLOWED_ORIGINS in README.md, and open a pull request.",
  "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 changes `app.py`, adds `tests/test_cors.py` and adds one paragraph to `README.md`. Its description pastes the `pytest` output with the four new tests named, the `pre-commit run --all-files` summary showing each hook passing, and the `curl -i` output of a preflight against the running app with the variable set.

Before merging, a reviewer decides whether the production origin list should live in the deployment's environment or in a settings module, whether `allow_methods` should widen before the first `POST` handler lands, and whether `allow_origin_regex` is a better fit for preview deployments with changing subdomains, which the description mentions and leaves off by default.

## Run it on every repository

A team with several Litestar services sends this body once per repository from its own server, each a `POST /o/{org}/sessions` with that 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: one with `POST` and `PATCH` handlers gets those in `allow_methods`, one with cookie sessions gets `allow_credentials=True` and an explicit origin list, and one that already has a `cors_config` ends with a note and no change.

Once CORS is in place, an automation on the Project with a `github` trigger on `pull_request.opened` and the prompt "if this pull request adds a route handler with a method not in allow_methods, or a custom response header not in expose_headers, comment with the handler and the missing entry" starts one run per pull request. The trigger adds the pull request after the prompt, and only work by an owner, member or collaborator fires it.

## Why run it on Rush?

CORS is usually added in a hurry with `allow_origins=["*"]` and then forgotten until a browser refuses a credentialed request. The agent reads which methods the app serves and writes the narrowest config that works, with a test for the preflight so a later change to the handlers cannot silently break the browser path.

In a repository where Ruff runs every rule and `mypy` is strict, the slow part of a small change is making the linters happy. The agent runs the project's own `pdm run lint` and `pdm run test` in its sandbox until they pass, and the output stays with the run for the reviewer.

## Frequently asked questions

### Why not allow every origin?

A wildcard with `allow_credentials` is refused by browsers, and without credentials it still lets any site read the API from a page. An explicit list from `ALLOWED_ORIGINS` keeps the decision in the deployment, and an empty list means no CORS headers, which is what the app does today.

### Does Litestar answer the preflight itself?

Yes. Giving the app a `cors_config` installs the middleware that answers `OPTIONS` requests carrying `Access-Control-Request-Method`, so no handler is added. The preflight test proves the `allow-methods` and `max-age` headers come back for `/sync`.

### Why a factory instead of configuring the module-level app?

The tests need apps with different origin lists, and a module-level `app` is built once at import. `create_app` takes the list as an argument and the module still exports `app = create_app()`, so `litestar run` and the existing tests are unchanged.

### Will it pass on Python 3.8?

The file already starts with `from __future__ import annotations`, so `list[str] | None` is never evaluated at runtime, and the environment parsing uses only `str.split` and `str.strip`. The CI matrix runs the tests on 3.8 through 3.11 as before.

## More Litestar jobs

- [Add Coverage to CI for a Litestar App](https://getrush.ai/run/add-coverage-to-ci/litestar/)
- [Add CSRF Protection to a Litestar App](https://getrush.ai/run/add-csrf-protection/litestar/)
- [Add Cursor Pagination to a Litestar API](https://getrush.ai/run/add-cursor-pagination/litestar/)

## The same job on other stacks

- [Add CORS to a Quarkus REST API](https://getrush.ai/run/add-cors/quarkus/)
- [Add CORS to a Rocket JSON API](https://getrush.ai/run/add-cors/rocket/)
- [Add CORS to a Serverless Framework API from a Linear Issue](https://getrush.ai/run/add-cors/serverless/)

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