# Add CORS to a Fiber API

Yes. An agent adds Fiber v3's cors middleware to your API group with an origin list from a flag or the environment, tests a preflight and a denied origin, in a PR.

[Run this on Rush](https://cloud.getrush.ai/run/add-cors/fiber/). 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 is assembled before it adds a header, because in Fiber the place a middleware is mounted decides which routes it covers. In a project like gofiber/boilerplate, `go.mod` names module `boilerplate` on Go 1.26 with `github.com/gofiber/fiber/v3` v3.6.1 and `github.com/gofiber/utils/v2`. `app.go` parses a `-port` flag defaulting to `:3000` and a `-prod` flag that turns on prefork, calls `database.Connect()`, builds `fiber.New(fiber.Config{})`, adds `recover.New()` and `logger.New()`, creates a `/api/v1` group with `GET /users` on `handlers.UserList` and `POST /users` on `handlers.UserCreate`, serves `./static/public` through the `static` middleware and ends with `handlers.NotFound`. `static/public/js/app.js` calls `/api/v1/users` with `fetch` from the same origin, so nothing today needs CORS, and no `cors` import exists in the module. `database/database.go` is an in-memory slice behind a mutex, `models/user.go` has one `Name` field, there are no test files, `.github/workflows/test.yml` runs `go test ./... -v -race` on Go 1.26 and 1.27 on Linux and Windows runners, and `lint.yml` runs golangci-lint v2.14.0 with the `modernize` linter from `.golangci.yml`.

The middleware ships in the module at `github.com/gofiber/fiber/v3/middleware/cors`, so no dependency is added. In v3 its `Config` takes `AllowOrigins`, `AllowMethods` and `AllowHeaders` as `[]string`, where v2 took comma-separated strings, plus `ExposeHeaders`, `MaxAge` in seconds, `AllowCredentials` and `AllowPrivateNetwork`; the defaults allow `*` with `GET, POST, HEAD, PUT, DELETE, PATCH, QUERY`. Two of its rules shape the change. The middleware panics at startup on an origin that is not a bare scheme and host, so `example.com` without `https://` stops the process, and it panics on `AllowOrigins` containing `*` together with `AllowCredentials: true`. An empty `AllowOrigins` list allows every origin, so the agent must not install the middleware with an empty list by mistake.

The agent adds an `-origins` flag beside `-port` and `-prod`, a comma-separated list that falls back to a `CORS_ORIGINS` environment variable, splits and trims it into a slice, and mounts `cors.New(cors.Config{AllowOrigins: origins, AllowHeaders: []string{"Origin", "Content-Type", "Accept"}, AllowMethods: []string{fiber.MethodGet, fiber.MethodPost, fiber.MethodOptions}, MaxAge: 600})` on the `v1` group with `v1.Use(...)`, so the static files and the 404 page keep their same-origin behaviour and only the API answers cross-origin. When no origin is configured the middleware is not mounted at all, and the startup log says so, which keeps the empty-list-allows-all rule from ever applying. Because the config panics on a malformed entry, the agent validates each origin with `url.Parse` and refuses to start with a clear message naming the bad value, rather than letting the middleware's redacted panic be the first sign. To make this testable it moves the router construction out of `main` into `newApp(origins []string) *fiber.App`, which `main` calls after parsing flags.

The tests go in `app_test.go` and use `app.Test` with `httptest.NewRequest`. A preflight `OPTIONS /api/v1/users` with `Origin: https://app.example.com` and `Access-Control-Request-Method: POST` from an allowed origin answers 204 with `Access-Control-Allow-Origin` echoing that origin, the methods and headers lists, and `Access-Control-Max-Age: 600`; a `GET /api/v1/users` with `Origin: https://evil.example` gets the users but no `Access-Control-Allow-Origin` header; a `GET /` for the static page carries no CORS headers at all; and `newApp(nil)` serves the API with no CORS headers, which pins the not-mounted case. A table test on the origin parser covers trailing slashes, a missing scheme and surrounding spaces. The agent runs `go vet ./...`, `go test ./... -v -race` as `test.yml` does and `golangci-lint run` with the repository's config, starts the server with `-origins https://app.example.com` and curls a preflight to paste into the pull request, and documents the flag and the variable in `README.md`.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add CORS to this Fiber v3 API. Read go.mod, app.go, handlers/handlers.go, database/database.go, models/user.go, static/public/js/app.js, README.md, .golangci.yml and the workflows under .github/workflows first. Use the cors middleware from github.com/gofiber/fiber/v3/middleware/cors. Add an -origins flag, comma-separated, with a CORS_ORIGINS environment variable fallback, validate each origin as a scheme and host and exit with a clear message on a bad one, and mount the middleware on the /api/v1 group only, with explicit AllowOrigins, AllowHeaders, AllowMethods and a MaxAge, never with a wildcard and credentials together; when no origin is configured do not mount it, since an empty AllowOrigins allows every origin. Move router construction into a newApp function so it can be tested. Write tests with app.Test for an allowed preflight, a GET from a non-listed origin receiving no allow-origin header, the static route receiving no CORS headers, and the unconfigured case, plus a table test for the origin parser. Run go vet, go test -race and golangci-lint, start the server and curl a preflight, document the flag and variable in the README, 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

What comes back is a pull request that changes `app.go` and `README.md` and adds `app_test.go`. The description shows the preflight response from the running server with its `Access-Control-Allow-Origin`, `Access-Control-Allow-Methods`, `Access-Control-Allow-Headers` and `Access-Control-Max-Age` headers, the response to a request from a non-listed origin without them, and the `go test -race` output listing the new cases.

The run's record keeps `go vet`, the race run, the lint run and the two curls, so a reviewer can see the denied origin got no header rather than infer it from the code.

Before merging, a reviewer decides whether the front end will ever send cookies or an `Authorization` header, which would mean `AllowCredentials: true` and that header in `AllowHeaders`, whether subdomain patterns such as `https://*.example.com` should be accepted by the flag, and whether the origin list should move into a config file alongside the port. Handlers, the in-memory store and the static front end are unchanged.

## Run it on every new frontend origin

A team with several Fiber services 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 service's own router and mounts the middleware on the group that is actually called cross-origin, and each opens its own pull request.

After that, an automation on the Project with a `github` trigger on `pull_request.opened` and `pull_request.synchronize` and the prompt "if this pull request changes the cors configuration or adds a route group, check that no wildcard origin is combined with credentials and that new API routes sit under the group the middleware covers, and comment with what you find" reviews every later change. The trigger puts 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?

CORS is three headers and a dozen ways to get them wrong: a wildcard that leaks an authenticated API, an origin written without its scheme that panics at startup, a middleware mounted on the whole app that puts allow headers on the static site, or an empty list that silently means everyone. The agent reads the v3 middleware's rules, mounts it on the one group that needs it and writes the denied case as a test, so the pull request shows the header absent where it should be.

Running it on Rush means the race run, the lint and the live preflight happen in the run's own sandbox with the output kept, so the reviewer reads what the server answered rather than what the code intends. A team with several Go services can send one run each and review each pull request on its own.

## Frequently asked questions

### Why not just app.Use(cors.New())?

The default config allows every origin, which is fine for a public read-only API and wrong for anything with sessions or tokens. The default also covers the whole app, so the static pages and the 404 handler would start answering preflights. An explicit list on the `/api/v1` group says exactly which front ends may call the API and nothing more.

### Does the middleware affect the static files?

Not when mounted with `v1.Use`, because Fiber applies a middleware only to the group it is registered on. `GET /` and the assets under `static/public` keep their same-origin behaviour, and the test for the static route asserts that no `Access-Control-Allow-Origin` header is present.

### Why does Fiber panic on some configurations?

The v3 middleware refuses two configurations at startup rather than at request time: an entry in `AllowOrigins` that is not a bare scheme and host, and a wildcard origin combined with `AllowCredentials: true`, which browsers would reject and which would otherwise look like it works. The agent validates the flag's values first so a bad origin produces a readable message naming the value instead of the middleware's redacted panic.

### What changes if the front end needs cookies?

Set `AllowCredentials: true`, list the exact origins rather than a pattern, and add `Authorization` to `AllowHeaders` if a bearer token is sent. The pull request leaves this off because `static/public/js/app.js` sends neither, and it shows the three-line change for when a front end on another origin does.

## More Fiber jobs

- [Add CSRF Protection to a Fiber App](https://getrush.ai/run/add-csrf-protection/fiber/)
- [Add govulncheck to CI for a Fiber Multi-Module Repository](https://getrush.ai/run/add-govulncheck-to-ci/fiber/)
- [Add Graceful Shutdown to a Fiber App](https://getrush.ai/run/add-graceful-shutdown/fiber/)

## The same job on other stacks

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

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