# Add CSRF Protection to an htmx App

Yes. An agent adds a CSRF token to every form and every htmx request, keeps it fresh across boosted navigation, and proves each route refuses a request without it.

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

## What the agent does

An htmx app sends state-changing requests from places a classic form audit misses, so the agent starts by listing them. In an app like bigskysoftware/contact-app, a Flask app with htmx 1.8.0 vendored at `static/js/htmx-1.8.0.js`, `app.py` has nine routes that accept `POST`, `PUT` or `DELETE`. Six serve the HTML pages, and the templates reach those in more ways than one: the plain forms in `new.html` and `edit.html`, which `<body hx-boost="true">` in `layout.html` turns into AJAX; the `hx-delete` link inside each row's menu in `rows.html`; the `#delete-btn` button in `edit.html`; the `hx-post` and `hx-delete` buttons in `archive_ui.html`; and, for the bulk delete in `index.html`, both an `hx-delete` button and an Alpine handler that calls `htmx.ajax('DELETE', '/contacts', ...)`. `requirements.txt` pins Flask 2.1.2 and has no CSRF library, and no template carries a token.

It adds Flask-WTF at a version that installs beside those pins and initialises `CSRFProtect` on the app, which checks `POST`, `PUT`, `PATCH` and `DELETE` for a token in a `csrf_token` form field or an `X-CSRFToken` header. The two forms get a hidden `csrf_token` input, so they still work when JavaScript is off. Every other request gets the header from one `hx-headers` attribute that descendants inherit. Where that attribute sits matters in this app: a boosted navigation replaces the inside of `<body>` and leaves the tag's own attributes as they were on the first full page load, and a Flask-WTF token is valid for an hour by default. The agent puts `hx-headers` on `<main>`, which every response renders again, so a tab left open all afternoon still sends a current token. The bulk delete passes the form as `source`, which sits inside `<main>`, so it inherits the header as well.

Then it decides what a refusal looks like. htmx does not swap a 4xx response by default, so a rejected click would do nothing visible. The agent registers a handler for Flask-WTF's `CSRFError` that answers a normal request with a short page and an htmx request with an `HX-Refresh: true` header, so the page reloads with a new token. It looks at the JSON routes under `/api/v1/contacts` separately: they read form fields, have no authentication and are meant for clients that hold no session, so the agent exempts them with `@csrf.exempt` and writes that down as a finding of its own. It also moves `app.secret_key`, which is the literal `b'hypermedia rocks'` in `app.py`, to a `SECRET_KEY` environment variable, because the token and the session are signed with it.

The repository has no tests, so the agent adds pytest tests with Flask's test client: each of the six HTML routes answers 400 with no token, the forms pass with the field, the htmx routes pass with the header, a token from another session is refused, and the three `/api/v1` routes still work without one. `Contact.save_db()` rewrites `contacts.json` in the working directory on every save, so the tests run against a copy in a temporary directory. Last, it starts `python app.py`, opens the app in the sandbox's browser and performs each action by hand: create a contact, edit one, delete from a row menu, select two rows and bulk delete, start and clear the archive download. It records the request headers for each from the browser's network panel.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "A Linear issue labelled security says this Flask and htmx app has no CSRF protection. Read requirements.txt, app.py, contacts_model.py and every file under templates first, and list every route that accepts POST, PUT, PATCH or DELETE together with each place in the templates that calls it: plain forms, hx-post, hx-put and hx-delete attributes, and any htmx.ajax call in inline script. Add Flask-WTF at a version that installs with the pinned Flask and enable CSRFProtect. Put a hidden csrf_token input in every form so it works without JavaScript. Send the token on every htmx request with one hx-headers attribute; the body tag has hx-boost, so put the attribute on an element that each response renders again, not on the body tag, and explain why in the pull request. Handle CSRFError: a short page for a normal request, and an HX-Refresh response header for an htmx request. Decide for the JSON routes under /api/v1 whether to exempt them, say what you decided and why, and report their missing authentication as a separate finding without fixing it. Read the secret key from a SECRET_KEY environment variable. Add pytest tests with the Flask test client, run against a temporary copy of contacts.json: every protected route refuses a request with no token, accepts one with the field or the header, and refuses a token from another session, and any exempt route still works without one. Start the app, open it in the browser, perform create, edit, row delete, bulk delete and the archive buttons, and record the request headers of each. Open a pull request that links the issue.",
  "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 `requirements.txt`, `app.py`, `templates/layout.html`, `templates/new.html` and `templates/edit.html`, and adds a `tests` directory. Its description opens with the table the agent built first: each state-changing route, the template and attribute that calls it, and whether the token travels as a form field or a header. Under it are the pytest output and, for each action performed in the browser, the request line and the `X-CSRFToken` header as the network panel showed them.

It names what it left alone. The `/api/v1/contacts` routes are exempt and still accept a write from anyone who can reach the server, which is a missing-authentication problem a token would not solve. The app has no login, so today the token protects one case: a page on another site driving the browser of someone who can reach the app, for example on an office network. The description says the same change covers signed-in users the day a login is added.

A reviewer checks three things before merging: that `SECRET_KEY` is set wherever the app is deployed, since the literal is gone; that the `hx-headers` attribute is on `<main>` and that no template renders a state-changing control outside it; and that any other client of the HTML routes, such as a script that posts to `/contacts/new`, is known and updated.

## Run it on every Linear issue labelled security

Connect Linear in the console under Settings → Connections, then add an automation to the Project that holds the repository, with a `linear` trigger on `linear.issue.labeled` and the label `security`. Keep the saved prompt general: read the issue, list the routes and the template calls it concerns, add the protection, test it and open a pull request that links the issue. The trigger puts the issue after that prompt, so a label on "forms have no CSRF token" and a label on "session cookie is not HttpOnly" each start their own run. It fires only when a person in your Rush org adds the label.

A security backlog tends to arrive in bursts after an audit. The automation's max runs per hour, from 1 to 30, decides how many start in an hour; an issue labelled past that waits as a `queued` run and starts when the hour has room.

## Why run it on Rush?

CSRF protection on an htmx app fails in ways only a browser shows: a boosted page that keeps a stale token, a delete link that sits outside the element carrying the header, an Alpine handler that builds its own request. The agent's sandbox has a browser, so it clicks every control against the running app and keeps the request headers it saw. A reviewer reads those in the pull request and does not have to check out the branch to find the one button that was missed.

The work is also tedious in the way that gets skipped. Nine routes, a handful of ways of calling them and a test for each is an afternoon nobody schedules. As a run it happens while the team does something else, with every command and its output kept in the transcript, and it ends as a pull request with the tests that would catch the next template that forgets the token.

## Frequently asked questions

### Why not put the token on the body tag?

With `hx-boost`, htmx replaces what is inside `<body>` on each navigation and keeps the tag itself, so an attribute on it holds the token from the first full page load. Flask-WTF tokens expire after an hour by default. On an element inside the body, each response brings a fresh one.

### Does this work with Django, Rails or Laravel instead of Flask?

The htmx half is the same: one inherited `hx-headers` attribute, or a hidden field in each form. The server half uses the framework's own middleware and header name, which the agent reads from the repository's dependencies before it changes a template.

### Will scripts that call the JSON API break?

Not in the pull request as described: the `/api/v1` routes are exempt, and a test asserts they still accept a request with no token. If your API is called from the browser with a session cookie, say so in the issue and the agent protects it with the same header.

### What happens when a token does expire?

The server answers 400. For an htmx request the handler adds `HX-Refresh: true`, so the page reloads and the next click carries a new token. A plain form submission gets a short page that says to go back and try again.

## More htmx jobs

- [Add Infinite Scroll to an htmx App](https://getrush.ai/run/add-infinite-scroll/htmx/)
- [Add Loading Indicators to an htmx App](https://getrush.ai/run/add-loading-indicators/htmx/)
- [Upgrade htmx 1 to htmx 2](https://getrush.ai/run/upgrade-htmx/htmx/)

## The same job on other stacks

- [Add CSRF Protection to Ktor Form Posts](https://getrush.ai/run/add-csrf-protection/ktor/)
- [Add CSRF Protection to a Litestar App](https://getrush.ai/run/add-csrf-protection/litestar/)
- [Add CSRF Protection to a Node.js App](https://getrush.ai/run/add-csrf-protection/nodejs/)

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