# Add CORS to a CodeIgniter 4 API

Yes. An agent configures CodeIgniter 4's built-in CORS filter for your API routes, adds the OPTIONS routes preflights need, tests both, and opens a PR.

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

## What the agent does

The agent reads what the framework already provides before writing a filter, because CodeIgniter 4 ships CORS and the work is in configuring and applying it rather than writing it. In an app started from codeigniter4/appstarter, `composer.json` requires `php` ^8.2 and `codeigniter4/framework` ^4.7, with PHPUnit ^10.5.16 for development. `app/Config/Filters.php` already aliases `cors` to `CodeIgniter\Filters\Cors`, beside `csrf`, `secureheaders` and the rest, but `$globals`, `$methods` and `$filters` apply none of them. `app/Config/Cors.php` holds a `$default` array with `allowedOrigins`, `allowedOriginsPatterns`, `allowedHeaders`, `exposedHeaders` and `allowedMethods` all empty, `supportsCredentials` false and `maxAge` 7200. `app/Config/Routes.php` has one route, `/` to `Home::index`, `app/Config/Routing.php` sets `$autoRoute` to false, and `app/Config/App.php` sets `baseURL` to `http://localhost:8080/`. `tests/unit/HealthTest.php` is the only test, `phpunit.dist.xml` boots from the framework's `system/Test/bootstrap.php`, and `.github/workflows/phpunit.yml` runs the suite on PHP 8.2 and 8.5.

A CORS filter with every list empty allows nothing, so the agent fills the config from the question it was asked rather than with a wildcard. It adds a named config, `public array $api`, to `app/Config/Cors.php` with `allowedOrigins` holding the front end's origin read from a new `cors.allowedOrigins` entry in `env`, split on commas, so staging and production differ by environment and not by code, `allowedHeaders` of `Content-Type`, `Authorization` and `X-Requested-With`, `allowedMethods` of `GET`, `POST`, `PUT`, `PATCH` and `DELETE`, `exposedHeaders` empty, `supportsCredentials` false, and the default `maxAge`. The `$default` array stays empty, so a route that is not opted in sends no CORS headers at all, which the pull request calls out as the safe direction.

Applying it is a routing change. The user guide is explicit that controller filters do not run for a route that does not exist, so a preflight `OPTIONS` to a path with only a `GET` route is a 404 before the filter can answer. The agent adds an `api` group in `app/Config/Routes.php` with `['filter' => 'cors:api']`, puts a small `Api\Health` controller answering `GET api/health` in it as the first route so the group has a member, and adds `$routes->options('api/(:any)', static function () {})` inside the group so preflights reach the filter, which answers them itself without calling the closure. The filter argument `api` selects the named config, so a later group for a public endpoint can use `cors:public` with a different origin list. The pull request shows `php spark routes` with the filter listed against each route.

Tests use the framework's `FeatureTestTrait`, which sends requests through the full filter chain. `tests/feature/CorsTest.php` sends `GET api/health` with an `Origin` from the allowed list and asserts `Access-Control-Allow-Origin` echoes it, sends the same with an origin not in the list and asserts the header is absent, sends `OPTIONS api/health` with `Access-Control-Request-Method: POST` and the allowed origin and asserts a 204 with `Access-Control-Allow-Methods` and `Access-Control-Max-Age`, and sends `GET /` with an `Origin` and asserts no CORS header, since the root is outside the group. In the sandbox the agent runs `composer install` and `vendor/bin/phpunit`, starts `php spark serve`, and runs `curl -i` for a preflight and a simple request before opening the pull request.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add CORS to this CodeIgniter 4 app's API. Read composer.json, app/Config/Filters.php, app/Config/Cors.php, app/Config/Routes.php, app/Config/Routing.php, app/Config/App.php, env, phpunit.dist.xml, tests/unit/HealthTest.php and .github/workflows/phpunit.yml first. Do not write a filter; use the cors alias that Filters.php already declares. Add a named config public array $api to app/Config/Cors.php whose allowedOrigins come from a cors.allowedOrigins entry in env split on commas, with allowedHeaders Content-Type, Authorization and X-Requested-With, allowedMethods GET, POST, PUT, PATCH and DELETE, supportsCredentials false and the default maxAge; leave $default empty. In app/Config/Routes.php add an api group with filter cors:api containing a GET api/health route to a small Api\\Health controller and an options route for api/(:any) with an empty closure so preflights reach the filter. Add tests/feature/CorsTest.php using FeatureTestTrait that checks an allowed origin is echoed on GET api/health, a disallowed origin gets no header, a preflight OPTIONS with Access-Control-Request-Method POST gets 204 with the methods and max-age headers, and GET / gets no CORS header. Document the env entry in env and README.md. Run composer install, vendor/bin/phpunit and php spark routes, start php spark serve and curl -i a preflight and a simple request, then open a pull request that pastes the curl output and the routes table.",
  "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 that changes `app/Config/Cors.php`, `app/Config/Routes.php`, `env` and `README.md`, and adds `app/Controllers/Api/Health.php` and `tests/feature/CorsTest.php`. The description pastes `php spark routes` with `cors:api` against the group's routes, and `curl -i` output for the preflight, showing `204`, `Access-Control-Allow-Origin` with the configured origin, `Access-Control-Allow-Methods` and `Access-Control-Max-Age: 7200`, and for the simple request, showing the origin echoed on the JSON response.

The run's record holds `composer install`, the PHPUnit run with `HealthTest` and the four new cases, the routes listing and the two requests. The existing `Home` route and the filter aliases are unchanged; nothing outside the `api` group gains a header.

Before merging, a reviewer sets the real origins for each environment in `.env`, decides whether `supportsCredentials` must be true because the front end sends cookies, in which case the origin list cannot contain a wildcard, and whether the `PHPUnit` workflow's PHP 8.5 job needs any change for the new test.

## Run it on every new CodeIgniter service

A team with several CodeIgniter 4 APIs starts one run per repository from its own server: one `POST /o/{org}/sessions` each, 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 rather than a second pull request. Each run reads that app's own routes and auto-routing setting, so an app with `$autoRoute` on gets the group written with explicit routes first, since the filter cannot cover routes that only exist by convention.

Afterwards, an automation on the Project with a `github` trigger on `pull_request.opened` and `pull_request.synchronize` and the prompt "if this pull request adds a route under api that is outside the cors:api group, or adds a method the options route does not cover, comment with the route and the fix" keeps a new endpoint from failing its first preflight. The trigger adds the pull request after the prompt; only work by an owner, member or collaborator fires it, never a fork's.

## Why run it on Rush?

The CORS mistake in CodeIgniter 4 is not the header list; it is the preflight that returns 404 because no `OPTIONS` route exists, and that only shows up from a browser on another origin. The agent reads the user guide's rule, writes the `options` route, and sends the preflight through the full filter chain in a feature test and with `curl` against a running server in its own sandbox, so the reviewer sees the `204` rather than reading that it should happen.

The sandbox keeps the test run, the routes table and the requests with the run, and the pull request cites them. For a team with many CodeIgniter apps, each gets its own run and its own pull request with origins read from that app's environment rather than one list pasted everywhere.

## Frequently asked questions

### Why not fill $default so every route gets CORS headers?

Because `$default` applies wherever the `cors` alias is used without an argument, and a filled default invites someone to add `cors` to `$globals` and open every route, including server-rendered pages, to cross-origin reads. A named `api` config applied to one group gives headers to exactly the routes that need them, and a second named config can cover a public endpoint with a different list.

### Why is the OPTIONS route needed?

CodeIgniter 4 runs controller filters only for routes that exist, so without an `OPTIONS` route the preflight is a 404 before the CORS filter sees it. The `$routes->options('api/(:any)', ...)` entry inside the group makes the route exist; the filter answers the preflight itself and the empty closure is never called. The feature test asserts the 204.

### Can the allowed origins be a wildcard?

Only without credentials. With `supportsCredentials` true, browsers reject a `*` origin, which is why the agent reads explicit origins from `cors.allowedOrigins` in `.env` and keeps credentials off until the reviewer turns them on with a real list. `allowedOriginsPatterns` in the same config takes a regular expression for a family of subdomains.

### Does this need a newer framework version?

The CORS filter was added in CodeIgniter 4.5, and `composer.json` requires ^4.7, so no. The `cors` alias in `Filters.php` is proof it is already there; the agent only configures and applies it.

## More CodeIgniter jobs

- [Add CSRF Protection to a CodeIgniter 4 App](https://getrush.ai/run/add-csrf-protection/codeigniter/)
- [Add Database Migrations to a CodeIgniter 4 App](https://getrush.ai/run/add-database-migrations/codeigniter/)
- [Write a Dockerfile for a CodeIgniter 4 App](https://getrush.ai/run/add-dockerfile/codeigniter/)

## The same job on other stacks

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

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