# Add Security Headers to a Cloudflare Worker

Yes. An agent reads what your Worker's HTML loads, adds a Content-Security-Policy and the other headers that fit it, tests them in the Workers pool, and opens a PR.

[Run this on Rush](https://cloud.getrush.ai/run/add-security-headers/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 the Worker and the page it serves before choosing a policy. In a Worker like the `d1-template` in cloudflare/templates, `wrangler.json` names the Worker, sets `compatibility_date` to 2025-10-08, binds a D1 database as `DB` and turns observability on; `package.json` pins `wrangler` 4.136.1 and `typescript` 5.9.3 and has a `check` script of `tsc && wrangler deploy --dry-run` but no test script and no `vitest` dependency; `tsconfig.json` is strict with `types` pointing at the generated `worker-configuration.d.ts`. `src/index.ts` exports a `fetch` handler that runs `SELECT * FROM comments LIMIT 3` through `env.DB.prepare` and returns `renderHtml(JSON.stringify(results))` with a single `content-type: text/html` header. `src/renderHtml.ts` is the page: it links a stylesheet from `static.integrations.cloudflare.com`, loads a header image from `imagedelivery.net`, has one inline `style` attribute on a `span`, no script at all, and one link to the Cloudflare docs. Those four facts decide the policy.

It adds `src/securityHeaders.ts` with one function that takes a `Response` and returns a new one with the headers set, so the handler stays one line longer and the policy lives in one place. The `Content-Security-Policy` it writes is built from what the page loads and nothing wider: `default-src 'none'`, `style-src https://static.integrations.cloudflare.com 'unsafe-inline'` because of the inline `style` attribute, `img-src https://imagedelivery.net`, `base-uri 'none'`, `form-action 'none'` and `frame-ancestors 'none'`. Beside it go `X-Content-Type-Options: nosniff`, `Referrer-Policy: strict-origin-when-cross-origin`, `Permissions-Policy` denying camera, microphone and geolocation, `Strict-Transport-Security` with a one-year `max-age`, and `Cross-Origin-Opener-Policy: same-origin`. The pull request explains the one concession, `'unsafe-inline'` for styles, and shows the alternative: move the single inline style into a class so the directive can drop it.

The handler in `src/index.ts` wraps its existing return in that function and otherwise does not change. The function sets the same headers on every response, so a future route that serves JSON gets the hardening too; the HTML-only directives do no harm there. Then it adds what the template lacks, a test setup: `vitest` and `@cloudflare/vitest-pool-workers` as dev dependencies, a `vitest.config.ts` that points the Workers pool at `wrangler.json`, a `test` script, and `test/index.test.ts` that fetches the page through `SELF`, asserts the status and the HTML, asserts each header's exact value, and parses the `Content-Security-Policy` to assert that every `https://` host named in `renderHtml.ts` appears in the right directive, so a later change to the page that adds a host fails the test rather than breaking the page in the browser.

Before opening the pull request it runs `npx tsc`, `npx vitest --run`, and `npx wrangler dev` with the local D1 seeded by the `seedLocalD1` script, then opens the page in a browser in its sandbox and reads the console for CSP violation reports; the headers are only right if the page still renders with its stylesheet and image. It pastes the test output and the response headers from a `curl -I` against the dev server into the pull request, and leaves `wrangler.json`, the migration and `renderHtml.ts` as they were.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add security headers to this Cloudflare Worker and open a pull request. Read wrangler.json, package.json, tsconfig.json, src/index.ts, src/renderHtml.ts and the migrations directory first, and list every external host, inline style and script the HTML uses. Add src/securityHeaders.ts with a function that returns a copy of a Response with Content-Security-Policy built only from what the page loads (default-src 'none', the exact style and image hosts, base-uri 'none', form-action 'none', frame-ancestors 'none'), plus X-Content-Type-Options nosniff, Referrer-Policy strict-origin-when-cross-origin, a Permissions-Policy denying camera, microphone and geolocation, Strict-Transport-Security with a one-year max-age, and Cross-Origin-Opener-Policy same-origin. Wrap the handler's response in src/index.ts with it. Add vitest and @cloudflare/vitest-pool-workers, a vitest.config.ts pointing at wrangler.json, a test script, and test/index.test.ts that fetches the page through SELF and asserts each header and that every https host in renderHtml.ts appears in the CSP. Run tsc, vitest --run and wrangler dev with the seeded local D1, open the page in a browser and check the console for CSP violations, and paste the test output and curl -I headers in the pull request. Do not change wrangler.json, the migration or renderHtml.ts.",
  "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 adds `src/securityHeaders.ts`, `vitest.config.ts` and `test/index.test.ts`, edits `src/index.ts` by one wrapped return and `package.json` by two dev dependencies and a `test` script, and leaves `wrangler.json`, `renderHtml.ts` and the migration untouched. The description lists each header and the reason for its value, names the single `'unsafe-inline'` concession and how to remove it, and pastes the `vitest` output and the `curl -I` response from the dev server.

On a repository whose CI runs the template's `check` script, `tsc` and the dry-run deploy run on the pull request; with the new `test` script in CI, the header assertions run too. The run's record keeps the browser session, so a reviewer can see the page rendered under the policy with an empty console.

A reviewer checks the CSP against the page one host at a time, decides whether `Strict-Transport-Security` belongs on a Worker behind a zone that already sets it, and whether to take the follow-up that moves the inline style into the stylesheet so `'unsafe-inline'` can go. Nothing in the change affects the D1 query or the data it shows.

## Run it on every Worker that serves HTML

A team with several Workers sends one `POST /o/{org}/sessions` per repository with this prompt and that repository in `resources`. Each run reads its own HTML, so a Worker that loads a script from a CDN gets a `script-src` with that host and nothing else, and a Worker that serves only JSON gets the headers without the HTML-only directives, and each run opens its own pull request. Send a `request_id` per request so a retried call returns the run it already started.

Give the key a `webhook_url` and every run it starts posts `run.completed` when its turn ends, with `data.session_url` to read the pull request link from. The key runs at most `max_concurrent` sessions at once, 4 by default; a request beyond that still creates its session with `202` and `status: "queued"`, and the headers run starts when a slot frees.

## Why run it on Rush?

A Content-Security-Policy copied from a blog post either breaks the page or allows everything. The right one is derived from what the page loads, and the only honest check is to serve the page under the policy and look at the browser console. A Rush sandbox has a computer and a browser in it, so the agent runs `wrangler dev` with the local D1, opens the page, reads the console and keeps that beside the `vitest` output in the run's record.

The result is a branch with the policy in one file, a test that ties the policy to the page's hosts, and a pull request that shows the headers as served, so the reviewer reads evidence rather than a header list. The same request works on any Worker that returns HTML, with or without a framework in front of it.

## Frequently asked questions

### Why 'unsafe-inline' for styles?

The template's `renderHtml.ts` has one inline `style` attribute on a `span`. A `style-src` without `'unsafe-inline'` would block it and the prompt forbids editing `renderHtml.ts`. The pull request says so and shows the follow-up: move that one rule into the stylesheet and drop the keyword.

### Does the policy break the stylesheet or the header image?

No. `style-src` names `static.integrations.cloudflare.com` and `img-src` names `imagedelivery.net`, the two hosts the page uses, and the test asserts both appear in the CSP. The browser check in the sandbox confirms the page renders with an empty console.

### Should HSTS be set on a Worker?

It is harmless when the zone already sends it and useful when it does not. The pull request sets a one-year `max-age` without `preload`, and the reviewer can drop the header if the zone's edge configuration already covers it.

### The template has no tests. Is adding Vitest part of this change?

Yes. The Workers pool is the way to assert response headers from the real handler with the D1 binding available, and the repository's own contributor guide asks for tests on every template. The pull request adds the config, the script and one test file, nothing else.

## More Cloudflare Workers jobs

- [Add a Staging Environment to a Cloudflare Worker](https://getrush.ai/run/add-staging-environment/cloudflare-workers/)
- [Add WebSockets to a Cloudflare Worker with Durable Objects](https://getrush.ai/run/add-websockets/cloudflare-workers/)
- [Fix Cloudflare Worker Errors From Its Logs](https://getrush.ai/run/fix-cloudflare-worker-errors/cloudflare-workers/)

## The same job on other stacks

- [Add Security Headers to a CodeIgniter 4 App](https://getrush.ai/run/add-security-headers/codeigniter/)
- [Add Security Headers to a Django REST Framework API](https://getrush.ai/run/add-security-headers/django-rest-framework/)
- [Add Security Headers to an Echo API](https://getrush.ai/run/add-security-headers/echo/)

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