# Add API Key Authentication to a Cloudflare Worker API

Yes. An agent adds a bearer key check in front of your Worker's OpenAPI routes, keeps the docs open, lists the scheme in the spec, tests it and opens a PR.

[Run this on Rush](https://cloud.getrush.ai/run/add-api-key-auth/cloudflare-workers/). 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 API is assembled before it puts a check in front of it. In a Worker shaped like the `chanfana-openapi-template` in cloudflare/templates, `package.json` pins `hono 4.11.1`, `chanfana 2.8.3` and `zod 3.25.67`, with `wrangler 4.136.1`, `vitest 4.1.10` and `@cloudflare/vitest-pool-workers 0.21.3` for development; `npm test` runs `wrangler deploy --dry-run` and then `vitest run --config tests/vitest.config.mts`, and `npm run cf-typegen` regenerates `worker-configuration.d.ts`. `wrangler.jsonc` names the Worker `chanfana-openapi-template`, points `main` at `src/index.ts`, and binds a D1 database as `DB`. `src/index.ts` builds `new Hono<{ Bindings: Env }>()`, installs an `onError` that answers `{ success: false, errors: [...] }`, wraps the app with `fromHono(app, { docs_url: "/", schema: { info: ... } })`, mounts `tasksRouter` at `/tasks` and registers `DummyEndpoint` at `POST /dummy/:slug`. The tasks router is five chanfana D1 auto endpoints, `GET /`, `POST /`, `GET /:id`, `PUT /:id` and `DELETE /:id`, and nothing on any of them checks a caller.

The key lives where Wrangler keeps secrets. The agent adds `API_KEY` as a secret, documented in a new `.dev.vars.example` (the `.gitignore` already excludes `.dev.vars*` except that example), with `wrangler secret put API_KEY` for deployment, and runs `cf-typegen` so `Env` carries it. The check is a Hono middleware in `src/auth.ts` registered with `app.use("/tasks/*", ...)` and `app.use("/dummy/*", ...)` before the routes are mounted, so `/` and `/openapi.json`, which chanfana serves for the docs, stay open. It reads `Authorization: Bearer <key>`, compares with `crypto.subtle.timingSafeEqual` over equal-length buffers, and on a missing or wrong key answers `401` in the same `{ success: false, errors: [{ code, message }] }` shape the `onError` handler uses, with `WWW-Authenticate: Bearer`.

The spec has to say the same thing. chanfana's documentation registers schemes through `openapi.registry.registerComponent("securitySchemes", ...)`, so the agent registers a `bearerAuth` scheme of type `http`, scheme `bearer`, and applies it to the guarded endpoints so the generated `/openapi.json` lists it and the docs page shows the authorize control. The agent fetches `/openapi.json` in a test and asserts the scheme is present, which keeps the spec and the middleware from drifting.

Tests already run inside the Workers runtime: `tests/vitest.config.mts` uses `cloudflareTest` with `wrangler.jsonc`, passes the D1 migrations as a `MIGRATIONS` binding, and `tests/apply-migrations.ts` applies them before each file. The agent adds `API_KEY: "test-key"` to the Miniflare `bindings` there, gives `tests/integration/tasks.test.ts` and `dummyEndpoint.test.ts` a shared header helper so the existing cases keep passing, and adds `tests/integration/auth.test.ts`: `GET /tasks` with no header answers `401`, with a wrong key answers `401`, with the right key answers `200`, `GET /` and `GET /openapi.json` answer `200` with no header, and the spec carries `bearerAuth`. It runs `npm test` in the sandbox, which includes the dry-run deploy, and pastes the output.

## Start it with one API call

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

```json
{
  "agent": "codex",
  "input": "Add API key authentication to this Cloudflare Worker and open a pull request. Read package.json, wrangler.jsonc, src/index.ts, src/types.ts, src/endpoints/tasks/router.ts, src/endpoints/dummyEndpoint.ts, tests/vitest.config.mts, tests/apply-migrations.ts and both test files first. Store the key as a Wrangler secret named API_KEY, add a .dev.vars.example that names it, and run cf-typegen so Env is typed. Write a Hono middleware in src/auth.ts that reads Authorization: Bearer, compares with crypto.subtle.timingSafeEqual, and answers 401 in the same success and errors shape the onError handler uses with a WWW-Authenticate header; register it on /tasks/* and /dummy/* before the routes and leave / and /openapi.json open. Register a bearerAuth security scheme with openapi.registry.registerComponent and apply it so the generated spec lists it. Add API_KEY to the Miniflare bindings in tests/vitest.config.mts, update the existing tests to send the header, and add tests/integration/auth.test.ts covering missing key, wrong key, right key, the open docs routes and the scheme in /openapi.json. Run npm test and paste the output in the pull request. Do not change the D1 endpoints or the migration.",
  "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 a new `src/auth.ts`, two `app.use` lines and the scheme registration in `src/index.ts`, a regenerated `worker-configuration.d.ts`, a `.dev.vars.example`, the `API_KEY` binding in `tests/vitest.config.mts`, a header helper in the two existing test files and a new `tests/integration/auth.test.ts`. The description shows the `401` body for a missing key, the `bearerAuth` entry from `/openapi.json`, and the output of `wrangler deploy --dry-run` and `vitest run` from the sandbox.

The template has no workflow of its own, so the pasted `npm test` output is the check; the repository that holds it runs its checks at the monorepo level. On a repository with a Vitest workflow the same cases run on the pull request.

A reviewer checks that the middleware is registered before the routers are mounted, that the docs routes are the only open ones, that the comparison is constant-time and refuses keys of a different length without an exception, and that no key value appears in the diff. Then they run `wrangler secret put API_KEY` for each environment before deploying.

## Run it on every Worker exposed to a partner

A team that hands a Worker to an outside caller sends one `POST /o/{org}/sessions` per repository with this prompt and the repository in `resources`. Each run reads its own routes, so a Worker that already serves `/openapi.json` gets the scheme registered in it, and one without docs gets the middleware alone. Each run opens its own pull request.

Give the API key a `webhook_url` and Rush POSTs `run.completed` when each turn ends, with `session_url` to read the pull request from, so the list of open routes can be reviewed before the key is issued.

## Why run it on Rush?

An auth check on a Worker is small and the mistakes are small too: a route left open because the middleware was registered after the router, a comparison that leaks timing, a spec that still says the API is public. In a Rush sandbox the agent runs the tests inside the Workers runtime that `@cloudflare/vitest-pool-workers` provides, with the secret as a test binding, and the `401` and `200` bodies and the generated spec are kept in the run's record.

The change spans four places that have to agree: the secret, the middleware, the spec and the tests. The agent does them in one pass, runs the dry-run deploy that `npm test` already includes before pushing, and the same request works unchanged on the next Worker.

## Frequently asked questions

### Why a bearer header and not a query parameter?

A header stays out of access logs and browser history, and `Authorization: Bearer` is the form the OpenAPI `http` scheme with `bearer` describes, so the docs page can send it. The middleware reads only that header.

### Why keep /openapi.json open?

So a caller can read the spec, see the `bearerAuth` scheme and know what to send. The spec describes no secret. If you want the docs private too, the middleware moves to `*`, which the pull request notes.

### How do the tests get the key?

Through the Miniflare `bindings` in `tests/vitest.config.mts`, next to the `MIGRATIONS` binding the template already passes. `SELF.fetch` then runs the Worker with `API_KEY` set, and no `.dev.vars` file is needed for the test run.

### Does it support more than one key?

Not in this change. One secret, one key, which is what a single partner integration needs. Per-caller keys stored in D1 with a lookup table is a different design, and the pull request says so.

## More Cloudflare Workers jobs

- [Add CORS to a Cloudflare Worker API](https://getrush.ai/run/add-cors/cloudflare-workers/)
- [Add a Cron Trigger to a Cloudflare Worker](https://getrush.ai/run/add-cron-trigger/cloudflare-workers/)
- [Add Cursor Pagination to a Cloudflare Worker on D1](https://getrush.ai/run/add-cursor-pagination/cloudflare-workers/)

## The same job on other stacks

- [Add API Key Authentication to a Django REST Framework Project](https://getrush.ai/run/add-api-key-auth/django-rest-framework/)
- [Add API Key Authentication to a Fiber App](https://getrush.ai/run/add-api-key-auth/fiber/)
- [Add API Key Authentication to a Koa API](https://getrush.ai/run/add-api-key-auth/koa/)

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