# Add Security Headers to a Leptos Axum App

Yes. An agent adds security headers to a Leptos Axum server with tower-http and a nonce-based CSP that keeps hydration working, checked by Playwright, in a PR.

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

## What the agent does

In a project generated from leptos-rs/start-axum, `Cargo.toml` depends on `leptos` and `leptos_router` 0.8, `leptos_meta`, and behind the `ssr` feature on `axum` 0.8, `tokio` and `leptos_axum`; there is no `tower-http`. `src/main.rs` builds `Router::new().leptos_routes(...)` with a `fallback` of `leptos_axum::file_and_error_handler(shell)` and `with_state(leptos_options)`, and serves it with `axum::serve`, so every response, pages and the `/pkg` assets alike, passes through that one router. `src/app.rs` renders the document shell with `<AutoReload>`, `<HydrationScripts>` and `<MetaTags>` in the head and links the stylesheet at `/pkg/<name>.css`. `end2end/` holds a Playwright project whose only test opens `http://localhost:3000/` and checks the title and heading, and `[package.metadata.leptos]` in `Cargo.toml` names `npx playwright test` as the `end2end-cmd`, `127.0.0.1:3000` as `site-addr` and port 3001 for live reload. `rust-toolchain.toml` pins nightly.

The headers that do not depend on the page are plain response headers, so the agent adds `tower-http` with the `set-header` feature to the `ssr` dependencies and stacks `SetResponseHeaderLayer::if_not_present` layers on the router in `src/main.rs`: `X-Content-Type-Options: nosniff`, `X-Frame-Options: DENY`, `Referrer-Policy: strict-origin-when-cross-origin`, a `Permissions-Policy` that turns off camera, microphone and geolocation, and `Cross-Origin-Opener-Policy: same-origin`. `Strict-Transport-Security` is added only when a `LEPTOS_HSTS` environment variable is set, because the starter serves plain HTTP on port 3000 and that header belongs to whatever terminates TLS.

Content-Security-Policy is the one that can break a Leptos app, because `<HydrationScripts>` emits inline module scripts and the WASM bundle needs `'wasm-unsafe-eval'`. Leptos ships the answer: with the `nonce` feature enabled on `leptos_axum`, the server generates a nonce per response and `HydrationScripts` and `AutoReload` put it on their script tags; `use_nonce()` from `leptos::nonce` reads it during rendering. The agent enables that feature and adds a `Meta` tag with `http_equiv` set to `Content-Security-Policy` in `shell()`, whose content is built from `use_nonce()`: `default-src 'self'`, `script-src 'strict-dynamic' 'nonce-...' 'wasm-unsafe-eval'`, `style-src 'self' 'nonce-...'`, `img-src 'self' data:`. When `leptos_options.env` is `DEV`, it appends a `connect-src` entry for the reload websocket on `reload_port`, so `cargo leptos watch` keeps working; in `PROD` that entry disappears. Because a meta tag cannot carry `frame-ancestors`, the `X-Frame-Options` header stays.

The check is end to end. `end2end/tests/headers.spec.ts` captures the response from `page.goto`, asserts each header value, reads the CSP meta tag and checks its nonce matches the one on the hydration script, and fails on any console message that mentions a Content Security Policy violation, which is how a wrong directive shows up. The agent runs `npm install` in `end2end/`, `npx playwright install chromium`, and `cargo leptos end-to-end`, which builds the site, starts the server and runs the Playwright suite, then `cargo leptos build --release` and a `curl -I` against the release binary, before opening the pull request.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add security headers to this Leptos Axum app. Read Cargo.toml, rust-toolchain.toml, src/main.rs, src/app.rs, src/lib.rs, end2end/package.json, end2end/playwright.config.ts and end2end/tests/example.spec.ts first. Add tower-http with the set-header feature as an ssr dependency and add SetResponseHeaderLayer::if_not_present layers to the router for X-Content-Type-Options nosniff, X-Frame-Options DENY, Referrer-Policy strict-origin-when-cross-origin, a Permissions-Policy that disables camera, microphone and geolocation, and Cross-Origin-Opener-Policy same-origin; add Strict-Transport-Security only when LEPTOS_HSTS is set. Enable the nonce feature on leptos_axum and add a Content-Security-Policy meta tag in shell() built from use_nonce() with default-src self, script-src strict-dynamic plus the nonce plus wasm-unsafe-eval, style-src self plus the nonce, img-src self and data, adding connect-src for the reload websocket only when leptos_options.env is DEV. Add end2end/tests/headers.spec.ts that asserts each header, checks the meta nonce matches the hydration script nonce, and fails on any CSP violation in the console. Run npm install in end2end, npx playwright install chromium, cargo leptos end-to-end and cargo leptos build --release until they pass, then open a pull request listing each header and why the CSP is a meta tag.",
  "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 changes `Cargo.toml`, `src/main.rs` and `src/app.rs`, adds `end2end/tests/headers.spec.ts`, and updates `end2end/package-lock.json` only if Playwright needed a bump. Its description is a table of the headers with the value each one carries, a copy of the rendered CSP from a `curl -I` against the release build with the nonce visible, and the Playwright summary from the sandbox.

It explains the two choices that matter: why the CSP travels in a meta tag (the nonce is generated while the page renders, so the policy that names it is written in the same pass) and why `X-Frame-Options` is kept beside it (a meta CSP cannot express `frame-ancestors`). It also says what is not covered: `Strict-Transport-Security` stays off until TLS is in front of the app, and third-party scripts, of which the starter has none, would each need the nonce or a hash.

Before merging, a reviewer decides whether the proxy or the app owns HSTS, adds any analytics or font origins the real app loads to the policy, and runs the suite once against a production build with `LEPTOS_HSTS` set to see the full header set.

## Run it on every pull request that adds a script or stylesheet

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 script, stylesheet, image origin or inline handler, check it against the Content-Security-Policy in src/app.rs, run cargo leptos end-to-end, and post a review that names any directive that must change' starts one run per push. The trigger adds the pull request after the prompt and fills in nothing else, so a pull request that embeds a chart library is reviewed against the policy before a browser console does it in production.

A team with several Leptos services sends this body once per repository from its own server, each `POST /o/{org}/sessions` 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. Each run reads its own `main.rs`: a service that already stacks a `tower-http` `CompressionLayer` gets the header layers beside it, and one on Actix gets the same headers through that framework's middleware with the pull request saying so.

## Why run it on Rush?

Security headers on a server-rendered WASM app are mostly ordinary, but the CSP is not: a policy copied from a plain Axum service blocks the hydration script, the WASM module or the dev reload socket, and the app silently stops being interactive. The agent reads how the shell is rendered, turns on the nonce support Leptos provides, and proves in a real browser in its sandbox that the page still hydrates and the console shows no violation.

The Playwright output, the `curl -I` capture and the diff stay with the run, so a reviewer sees every header on a real response rather than in a description. A team with several services runs the same request across all of them at once.

## Frequently asked questions

### Will the Content Security Policy break hydration?

Not with the nonce. Leptos' `nonce` feature puts a per-response nonce on the scripts `HydrationScripts` and `AutoReload` emit, `'strict-dynamic'` lets those scripts load the bundle, and `'wasm-unsafe-eval'` allows the WASM module. The Playwright test fails on any violation in the console, so a directive that breaks the page cannot merge.

### Why is the CSP a meta tag when the other headers are headers?

Because the nonce is generated during rendering, and the policy that names it must be written in the same response. A meta tag from `leptos_meta` does that in one place. The limitation is `frame-ancestors`, which a meta tag cannot carry, so `X-Frame-Options: DENY` stays as a header.

### What about Strict-Transport-Security?

It is only correct on HTTPS responses, and the starter listens on plain HTTP on port 3000. The pull request gates it behind a `LEPTOS_HSTS` environment variable so a deployment that terminates TLS in the app can turn it on, and one behind a proxy leaves it to the proxy.

### Does cargo leptos watch still reload?

Yes. In `DEV` the policy includes a `connect-src` entry for the reload websocket on the `reload_port` from `leptos_options`, which is 3001 in the starter. In `PROD` that entry is absent, so the production policy is tighter than the development one.

## More Leptos jobs

- [Add Structured Logging to a Leptos Axum App](https://getrush.ai/run/add-structured-logging/leptos/)
- [Add Tailwind CSS to a Leptos App](https://getrush.ai/run/add-tailwind/leptos/)
- [Add WebSockets to a Leptos App](https://getrush.ai/run/add-websockets/leptos/)

## The same job on other stacks

- [Add Security Headers to a Litestar App](https://getrush.ai/run/add-security-headers/litestar/)
- [Add Security Headers to a Node.js App](https://getrush.ai/run/add-security-headers/nodejs/)
- [Add Security Headers to a Nuxt App](https://getrush.ai/run/add-security-headers/nuxt/)

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