# Add CSRF Protection to a Hono App with Cookie Sessions

Yes. An agent puts Hono's csrf middleware in front of your cookie-authenticated API routes, leaves assets and docs open, tests it with app.request and opens a PR.

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

## What the agent does

The agent reads how requests reach the API before it blocks any. In a Hono app shaped like the `stytch-auth` workspace of honojs/examples, `package.json` pins `hono ^4.8.3`, `@hono/stytch-auth ^0.1.0`, `react ^19.1.0`, `react-router-dom ^7.6.2` and `vite ^6.3.5` with `@cloudflare/vite-plugin ^1.6.0`; `npm run dev` runs `vite`, `npm run build` runs `vite build`, `npm run deploy` builds and runs `wrangler deploy`, and there is no test script. `wrangler.jsonc` names the Worker `stytch-consumer-todo-list` with `api/index.ts` as its entry, the `nodejs_compat` flag, a `compatibility_date` of `2025-03-19`, a KV binding `TODOS` and an `ASSETS` binding with `run_worker_first` and single-page-application fallback. `api/index.ts` builds one `Hono` app, calls `cors()` with no options on every path, mounts `TodoAPI` under `/api` and hands everything else to `env.ASSETS.fetch`.

`api/TodoAPI.ts` is where the risk is. `GET /todos` runs `Consumer.authenticateSessionLocal()`, and `POST /todos`, `POST /todos/:id/complete` and `DELETE /todos/:id` run `Consumer.authenticateSessionRemote()`; all four identify the caller from the Stytch session the browser SDK keeps in cookies, and the handlers write to KV under that user's id. The React side in `src/Todos.tsx` calls them through `hc<TodoApp>` from `hono/client`, so a legitimate request carries a JSON body. A page on another site cannot send JSON with cookies without a preflight, but it can submit an HTML form with `text/plain` or `application/x-www-form-urlencoded` to `POST /api/todos`, and `c.req.json()` in the handler parses whatever body arrives. That is the request the middleware exists to stop.

Hono ships `csrf` in `hono/csrf`, so no dependency is added. The agent registers `app.use('/api/*', csrf({ origin: ... }))` in `api/index.ts` after `cors()` and before `.route('/api', TodoAPI)`, which keeps the asset mount untouched. The middleware checks only unsafe methods (not `GET`, `HEAD` or `OPTIONS`) and only form content types, and it answers `403 Forbidden` when neither the `Origin` nor the `Sec-Fetch-Site` check passes. `origin` is a function that compares the request's origin with `c.env.ALLOWED_ORIGINS`, a comma-separated `vars` entry the agent adds to `wrangler.jsonc` beside the KV binding, so the deployed `workers.dev` host and the `localhost:3000` dev server from `vite.config.ts` are both a setting rather than a literal in code. The app type becomes `new Hono<{ Bindings: Env }>()`, which `TodoAPI.ts` already uses, and `npm run cf-typegen` regenerates `worker-configuration.d.ts` so `ALLOWED_ORIGINS` is typed.

The workspace has no tests, so the agent adds `vitest` as a dev dependency, the way the `basic` workspace in the same repository pins `vitest ^1.5.0`, with a `test` script and `api/index.test.ts`. Each case calls `app.request` with an env object as the third argument: a `POST /api/todos` with `Content-Type: text/plain` and an `Origin` outside the list answers `403`; the same request with no `Origin` and no `Sec-Fetch-Site` answers `403`; the same request from an allowed origin gets past the middleware, so its status is whatever the Stytch session check returns, not `403`; a `GET /api/todos` from a foreign origin is not blocked by the middleware; and a `GET /` still reaches the asset mount. The agent runs `npm test`, `npm run build` and `npx wrangler deploy --dry-run` in the sandbox and pastes all three outputs.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add CSRF protection to this Hono Worker and open a pull request. Read package.json, wrangler.jsonc, vite.config.ts, api/index.ts, api/TodoAPI.ts, api/TodoService.ts and src/Todos.tsx first. Use the csrf middleware from hono/csrf, no new runtime dependency. Register it on /api/* after cors() and before the TodoAPI route, with origin as a function that matches the request origin against a comma-separated ALLOWED_ORIGINS var; add ALLOWED_ORIGINS under vars in wrangler.jsonc with the local dev origin, run cf-typegen so the binding is typed, and type the root app with Bindings. Do not change the cors() call, the asset mount or the Stytch handlers; note in the pull request what the wildcard cors() allows. Add vitest as a dev dependency with a test script and write api/index.test.ts using app.request with an env object: a form-encoded POST /api/todos from a foreign origin answers 403, one with no Origin and no Sec-Fetch-Site answers 403, one from an allowed origin is not answered 403 by the middleware, a GET /api/todos from a foreign origin is not blocked, and GET / still reaches the assets. Run npm test, npm run build and npx wrangler deploy --dry-run and paste the output in the pull request.",
  "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 handful of lines in `api/index.ts`: the `csrf` import, the typed `Hono` constructor and one `app.use('/api/*', csrf({ ... }))` call; a `vars` block in `wrangler.jsonc`; a regenerated `worker-configuration.d.ts`; `vitest` and a `test` script in `package.json`; and a new `api/index.test.ts` with five cases. The description shows the `403 Forbidden` response from the foreign-origin case and the output of `vitest`, `vite build` and the `wrangler deploy --dry-run` from the sandbox.

The example repository's only workflow file is `.github/dependabot.yml`, so the pasted test output is the check. On a repository with a Vitest workflow the same cases run on the pull request. Because the Stytch handlers need `STYTCH_PROJECT_ID` and `STYTCH_PROJECT_SECRET` from `.dev.vars`, the tests assert what the middleware decides and not what the session check decides, and the pull request says so.

A reviewer checks that the middleware is scoped to `/api/*` and not `*`, that `ALLOWED_ORIGINS` lists the production host exactly as the browser sends it in `Origin` (scheme and host, no path), that the dev origin matches the `port: 3000` in `vite.config.ts` and `wrangler.jsonc`, and that the JSON path the React client uses is unaffected. Then they set `ALLOWED_ORIGINS` for each environment before merging.

## Run it on every Worker with cookie sessions

A team with several Workers that read a session cookie sends one `POST /o/{org}/sessions` per repository with this prompt and that repository in `resources`. Each run reads its own routes, so a Worker whose API already checks a custom header gets a note instead of a second check, and a Worker that serves only JSON to a bearer token gets the explanation that the form-content-type check does not apply to it. 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 result from, so the origin lists can be checked against each frontend before anyone merges.

## Why run it on Rush?

A CSRF check is easy to add and easy to add wrong: scoped too wide it blocks the asset mount, scoped too narrow it misses a write route, and with the wrong origin string it blocks your own frontend in production. In a Rush sandbox the agent sends the real requests through `app.request` with `Origin`, `Sec-Fetch-Site` and `Content-Type` set the way a browser form would, and the responses are kept in the run's record beside the test output, so the pull request shows what an attacker's page would get and what your own page would get.

The change is a few lines, but the proof is the work: deciding where the middleware sits relative to `cors()` and the Stytch handlers, wiring the var through `wrangler.jsonc` and the generated types, and writing the cases. The agent does that in one pass, runs the build and the dry-run deploy before pushing, and the same request works unchanged on the next Worker.

## Frequently asked questions

### Why does it only check form content types?

Because `hono/csrf` checks requests whose content type a browser form can send: `application/x-www-form-urlencoded`, `multipart/form-data` and `text/plain`, with a missing content type treated as `text/plain`. A cross-site JSON request already needs a preflight that the `cors()` call without `credentials` does not approve for cookies, so the middleware covers the path a form can reach.

### Does this change the cors() call?

No. The agent leaves `cors()` as it is and notes in the pull request that with no options it answers `Access-Control-Allow-Origin: *` without credentials. Narrowing it is a separate change a reviewer can ask for.

### Will the React client keep working?

Yes. `src/Todos.tsx` calls the API through `hc` with JSON bodies from the same origin, so the requests either are not form content types or pass the `Sec-Fetch-Site: same-origin` check. The test for an allowed origin shows the middleware letting the request through to the session check.

### What about the Stytch secrets in tests?

The tests pass only `ALLOWED_ORIGINS` in the env object, so the handlers behind the middleware have no Stytch credentials. The cases assert the middleware's `403` or its absence, and the pull request says the session checks themselves are not exercised.

## More Hono jobs

- [Add Cursor Pagination to a Hono API on Workers KV](https://getrush.ai/run/add-cursor-pagination/hono/)
- [Set Up GitHub Actions CI for a Hono Worker](https://getrush.ai/run/add-github-actions-ci/hono/)
- [Add Health Check Endpoints to a Hono API](https://getrush.ai/run/add-health-checks/hono/)

## The same job on other stacks

- [Add CSRF Protection to an htmx App](https://getrush.ai/run/add-csrf-protection/htmx/)
- [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/)

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