# Add API Key Authentication to a Fiber App

Yes. An agent guards your Fiber v3 API group with the built-in keyauth middleware, reads keys from the environment, compares them in constant time, and opens a PR.

[Run this on Rush](https://cloud.getrush.ai/run/add-api-key-auth/fiber/). 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 before it guards anything. In an app laid out like gofiber/boilerplate, `go.mod` declares module `boilerplate` on `go 1.26.0` with `github.com/gofiber/fiber/v3 v3.6.1` and `github.com/gofiber/utils/v2 v2.6.3`. `app.go` parses `-port` (default `:3000`) and `-prod`, which turns on prefork through `fiber.ListenConfig{EnablePrefork: *prod}`, installs `recover` and `logger`, groups `GET /api/v1/users` and `POST /api/v1/users` under `v1`, serves `./static/public` with the `static` middleware and ends with `handlers.NotFound`. `handlers.UserCreate` copies `c.FormValue("user")` with `utils.CopyString` and appends to the slice behind a mutex in `database/database.go`; `models.User` has one field, `Name`. `static/public/js/app.js` fetches the user list on load and POSTs a `FormData` body with no header of its own. `.github/workflows/test.yml` runs `go test ./... -v -race` on Go 1.26.x and 1.27.x, on Ubuntu and Windows runners; `lint.yml` runs golangci-lint v2.14.0 with `--tests=false`, and `.golangci.yml` enables `modernize`. There are no test files and no dependency on an auth library.

No new module is needed: Fiber v3 ships `github.com/gofiber/fiber/v3/middleware/keyauth`, and the agent uses it rather than writing a header check by hand. `keyauth.New` panics without a `Validator`, so the agent adds `handlers/auth.go` with one: it reads `API_KEYS`, a comma-separated list, once at startup into a slice of SHA-256 digests, hashes the presented key and compares with `crypto/subtle.ConstantTimeCompare`, so a wrong key costs the same time as a right one. The key arrives in an `X-API-Key` header through `extractors.FromHeader("X-API-Key")`; the default extractor, `extractors.FromAuthHeader("Bearer")`, is left in a comment for teams that prefer `Authorization`. A `Next` function returns true for `GET`, so the public user list keeps working from a browser while `POST /api/v1/users` needs a key. The `ErrorHandler` answers `401` with `{"success": false, "error": "missing or invalid API Key"}`, the same `fiber.Map` shape the existing handlers return, instead of the middleware's plain-text default; `keyauth.ErrMissingOrMalformedAPIKey` is the error it receives for a missing header.

`app.go` changes in one place: `v1 := app.Group("/api/v1", keyauth.New(cfg))`. The static route, the 404 handler, `recover` and `logger` are untouched, and because the key is read from the environment before `app.Listen`, every preforked child under `-prod` sees the same list. When `API_KEYS` is empty the app logs a warning and starts with the write route closed to everyone, which is safer than open; the README says to pass `-e API_KEYS=...` to the `docker run` line it already documents. `app.js` gains one header on its POST, read from a value the page asks for once and keeps in `localStorage`, with a note that a real deployment issues a key per client rather than sharing one in a browser.

`handlers/auth_test.go` drives the app with `app.Test` and `httptest.NewRequest`: a POST with no header expects `401`, a POST with a wrong key expects `401` and the JSON error body, a POST with a right key expects `200` and the created user in the response, and a GET with no header expects `200`. A last test sets `API_KEYS` to two keys and checks both pass, since the first deployment usually rotates a key by adding the new one before removing the old. The agent runs `go test ./... -race` and `golangci-lint run --tests=false` before the pull request opens, and `modernize` has nothing to say about the new file because it uses `strings.SplitSeq` where it iterates.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add API key authentication to this Fiber v3 app. Read go.mod, app.go, handlers/handlers.go, database/database.go, models/user.go, static/public/js/app.js, Dockerfile, README.md, .golangci.yml and the workflows under .github first. Use the built-in github.com/gofiber/fiber/v3/middleware/keyauth: create handlers/auth.go that reads API_KEYS (comma-separated) from the environment at startup, stores SHA-256 digests, and validates with crypto/subtle.ConstantTimeCompare. Extract the key from an X-API-Key header, skip the check for GET requests so the public list keeps working, and answer 401 with the same {success:false, error:...} JSON shape the handlers use. Apply it to the /api/v1 group only. Send the header from app.js, document API_KEYS in the README including the docker run line. Write handlers/auth_test.go with app.Test covering missing key, wrong key, right key, GET without a key, and two keys configured at once. Run go test ./... -race and golangci-lint run --tests=false, then open a pull request that quotes both outputs.",
  "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 adds `handlers/auth.go` and `handlers/auth_test.go`, changes `app.go` (the group gains the middleware), `static/public/js/app.js` (one header on the POST) and `README.md` (the `API_KEYS` variable and the `docker run -e` line). `go.mod` does not change, because `keyauth` and `extractors` live in the Fiber module the app already requires. Its description quotes the `go test -race` run and the lint run, and shows three `curl` calls: a POST with no key, a POST with a key, and the GET that still answers without one.

A reviewer reads the validator first, looking for the two mistakes API key code tends to have: a comparison with `==` instead of a constant-time one, and a key that reaches a log line. The `logger` middleware prints method, path, status and latency by default, so headers stay out of the log, and the test for two configured keys shows that rotation works without a restart gap. They then decide whether `GET /api/v1/users` should stay public, which the page treats as a product choice rather than a security one, and whether the key belongs in `X-API-Key` or `Authorization: Bearer` for their clients.

Nothing about storage changes: keys live in the environment, not in the in-memory user slice, and the pull request says so, with a per-client key table named as the next step once the app has a database.

## Run it on every Linear issue labelled auth

An automation on the Project with a `linear` trigger on `linear.issue.labeled` and the label `auth` starts one run per issue that asks for a guarded endpoint. The trigger adds the issue after the prompt and fills in no placeholder, so the prompt tells the agent to read the route names from the issue and to reuse the validator in `handlers/auth.go` once it exists rather than adding a second one. An automation's run is read-only, so it posts its plan and the diff it would make as a comment, and a person starts the run that pushes.

A team with several Fiber services sends this body once per repository from its own server, each `POST /o/{org}/sessions` naming that repository in `resources` with a `request_id` that is a UUID v5 of the repository name, so a retried call returns the run it already started. Each run reads its own `app.go` and decides which group gets the middleware.

## Why run it on Rush?

Authentication code is short and the bugs in it are quiet: a comparison that leaks timing, a `Next` that skips more than it should, a header name the client never sends. The agent runs the real app in its own sandbox, drives it with requests that carry no key, a wrong key and a right key, runs the suite under the race detector because prefork and a mutex are in play, and keeps the output with the pull request. A reviewer starts from a passing test, not from a diff they have to execute in their head.

The work is the same across a fleet of small Go services and different in each one: which group to guard, which routes stay public, where the keys come from. Starting one run per repository at once gives one pull request per service, each specific to the `app.go` it found, instead of a shared snippet pasted into ten places.

## Frequently asked questions

### Does this need a new dependency?

No. `keyauth` and `extractors` are packages inside `github.com/gofiber/fiber/v3`, which the app already requires at v3.6.1. `go.mod` and `go.sum` stay as they are.

### Which header carries the key?

`X-API-Key`, through `extractors.FromHeader`. The middleware's default is `extractors.FromAuthHeader("Bearer")`, and switching is a one-line change the pull request points at. The middleware can also chain extractors so a key in a query string or a cookie is accepted, which the page leaves off because browsers cache query strings in history.

### Why are the keys hashed if they are compared in memory anyway?

So the process holds digests rather than the secrets themselves, and so the comparison with `crypto/subtle.ConstantTimeCompare` runs over fixed-length inputs. It costs nothing at this scale and removes a class of mistake.

### Does prefork change anything?

No. `API_KEYS` is read before `app.Listen`, and each forked child inherits the environment, so every process validates against the same list. Rotation is adding the new key, deploying, then removing the old one.

### Will the browser page still work?

The list does, because `GET` is skipped. Adding a user needs the key, which `app.js` sends from a value the page stores locally. The pull request is explicit that this is a demo pattern and that a public deployment issues keys per client.

## More Fiber jobs

- [Add Response Compression to a Fiber App](https://getrush.ai/run/add-compression/fiber/)
- [Add CORS to a Fiber API](https://getrush.ai/run/add-cors/fiber/)
- [Add CSRF Protection to a Fiber App](https://getrush.ai/run/add-csrf-protection/fiber/)

## The same job on other stacks

- [Add API Key Authentication to a Koa API](https://getrush.ai/run/add-api-key-auth/koa/)
- [Add API Key Authentication to a Litestar App](https://getrush.ai/run/add-api-key-auth/litestar/)
- [Add API Key Auth to a Serverless Framework API](https://getrush.ai/run/add-api-key-auth/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/)
