# Add Security Headers and a CSP to a React Router App

Yes. An agent adds Helmet to your React Router custom Express server with a per-request CSP nonce passed to Scripts, keeps the dev server working, and opens a PR.

[Run this on Rush](https://cloud.getrush.ai/run/add-security-headers/react-router/). 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 server and the document are put together. In an app shaped like the `node-custom-server` template in remix-run/react-router-templates, `server.js` builds an Express 5 app with `compression`, disables `x-powered-by`, and in production serves `build/client/assets` with a one-year `immutable` cache and `build/client` with a one-hour one before handing the request to the built `server/app.ts`; in development it mounts Vite's middleware and loads `server/app.ts` through `ssrLoadModule`. `server/app.ts` wraps `createRequestHandler` from `@react-router/express` and fills a `RouterContextProvider` in `getLoadContext`, which `app/routes/home.tsx` reads through the `valueFromExpressContext` context in `app/context.ts`. `app/root.tsx` preconnects to `fonts.googleapis.com` and `fonts.gstatic.com`, loads an Inter stylesheet from Google, and renders `<Scripts />` and `<ScrollRestoration />`, both of which emit inline scripts. There is no `helmet`, no CSP and no test runner; `npm run typecheck` runs `react-router typegen && tsc -b`.

It adds the headers in `server.js`, where every response passes. `helmet` joins `dependencies`, and an `app.use` before the static handlers sets a per-request nonce with `crypto.randomBytes` on `res.locals.cspNonce`, then calls `helmet()` with a `contentSecurityPolicy` whose `script-src` is `'self'` plus a function returning `'nonce-<value>'` for the current response, `style-src` of `'self'` and `https://fonts.googleapis.com`, `font-src` of `'self'` and `https://fonts.gstatic.com`, `img-src` of `'self'` and `data:`, `connect-src` of `'self'`, and `frame-ancestors 'none'`. `Referrer-Policy`, `X-Content-Type-Options` and `X-Frame-Options` come from Helmet's defaults, and `Strict-Transport-Security` is enabled only when a `TRUST_PROXY` variable says the app sits behind TLS, so a plain `docker run -p 3000:3000` does not pin a browser to HTTPS on localhost.

The nonce has to reach the two inline scripts React Router renders. `server/app.ts` sets a new `cspNonce` context, declared in `app/context.ts` beside `valueFromExpressContext`, from `res.locals.cspNonce` inside `getLoadContext`; a root `loader` in `app/root.tsx` returns it, and `Layout` reads it with `useRouteLoaderData("root")` and passes `nonce` to `<Scripts />` and `<ScrollRestoration />`. Because `Layout` also renders the `ErrorBoundary`, the nonce is read defensively so an error page still renders when the loader did not run. In development the Vite client injects its own inline script and opens a WebSocket, so when `NODE_ENV` is `development` the policy adds `'unsafe-inline'` to `script-src` and `ws:` to `connect-src`, and the production policy stays strict.

The agent proves both modes. It runs `npm run build` and `npm start`, requests `/` with `curl -I` and pastes the `Content-Security-Policy`, `Referrer-Policy` and `X-Frame-Options` headers, opens the page in its own browser with the console visible to confirm nothing is blocked and the Inter font loads, then runs `npm run dev` and confirms hot module replacement still connects under the relaxed development policy. It runs `npm run typecheck`, which covers the new context and the root loader, and builds the `Dockerfile` to show `server.js` and `helmet` end up in the final image.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add security headers and a Content Security Policy to this React Router app with a custom Express server and open a pull request. Read package.json, server.js, server/app.ts, app/context.ts, app/root.tsx, app/routes/home.tsx, vite.config.ts, tsconfig.node.json and Dockerfile first. Add helmet to dependencies. In server.js, before the static handlers, generate a per-request nonce with crypto.randomBytes on res.locals.cspNonce and register helmet() with a CSP: script-src 'self' plus the nonce, style-src 'self' and https://fonts.googleapis.com, font-src 'self' and https://fonts.gstatic.com, img-src 'self' and data:, connect-src 'self', frame-ancestors 'none'; add 'unsafe-inline' to script-src and ws: to connect-src only when NODE_ENV is development so Vite HMR works; enable Strict-Transport-Security only when a TRUST_PROXY variable is set. Declare a cspNonce context in app/context.ts, set it in getLoadContext in server/app.ts from res.locals, return it from a root loader in app/root.tsx and pass it as nonce to Scripts and ScrollRestoration in Layout, reading it defensively so the ErrorBoundary still renders. Run npm run typecheck, npm run build and npm start, curl -I the home page and paste the headers, open the page in a browser and confirm no CSP violation and the font loads, run npm run dev and confirm HMR connects, and build the Dockerfile. Paste the output in the pull request. Do not change routes or styling.",
  "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 `helmet` in `package.json` and `package-lock.json`, the nonce and `helmet()` middleware in `server.js`, the `cspNonce` context in `app/context.ts`, one line in `getLoadContext` in `server/app.ts`, and a root `loader` plus `nonce` props in `app/root.tsx`. The description pastes the `curl -I` headers from the production server, a screenshot of the browser console with no violations, the `npm run dev` output showing the client connected, the `typecheck` output and the Docker build summary.

The template has no CI workflow, so the pasted headers, the console screenshot and the type-check are the evidence. The agent pushes one commit for the server and one for the React Router side, so the policy and the nonce plumbing can be read separately.

A reviewer checks that the nonce is generated per request and never reused, that `script-src` has no `'unsafe-inline'` in production, that the font and stylesheet origins match what `root.tsx` actually loads, that the error page still renders with the nonce missing, and that `Strict-Transport-Security` is off unless `TRUST_PROXY` is set. Then they merge, set `TRUST_PROXY` in the TLS-terminated deployment, and tighten `connect-src` as the app gains APIs.

## Run it on every new deployment target

A team with several React Router apps on custom servers starts one run per repository with `POST /o/{org}/sessions`, this prompt and the repository in `resources`. Each run reads that app's `root.tsx` for the origins it really loads and its `server.js` for the middleware order, so an app with self-hosted fonts gets a tighter policy and one behind a known proxy gets HSTS on, and each ends in its own pull request. A `request_id` makes a retried call return the run it already started.

The key's `webhook_url` receives `run.completed` for each run it starts, with `session_url` for the result, so a script can post the pull request links to the team channel as they land.

## Why run it on Rush?

A Content Security Policy is wrong in one of two directions: too loose to matter or tight enough to blank the page, and the only way to know is to load the site and watch the console. In a Rush sandbox the agent builds and starts the real server, reads the headers with `curl`, opens the page in its own browser with the console open, and repeats under the dev server to see HMR still connects, keeping all of it in the transcript.

Nothing has to be built or run on the reader's laptop, and the nonce plumbing through `getLoadContext` and the root loader follows the shape the template already uses for `valueFromExpressContext`. The pull request shows the exact headers a browser will see, and the same request works for any React Router app served by Express.

## Frequently asked questions

### Why does the CSP need a nonce?

`<Scripts />` and `<ScrollRestoration />` render inline scripts that carry the route data and the scroll state, and a `script-src` without `'unsafe-inline'` blocks them. A nonce generated per request and passed to both components lets exactly those scripts run while everything else inline is refused.

### Will the Vite dev server still work?

Yes. The Vite client injects an inline script and connects over a WebSocket, which a strict policy would block, so in development the policy adds `'unsafe-inline'` and `ws:`. The production branch in `server.js` keeps the strict policy; the agent runs both to show it.

### Why is HSTS behind a variable?

`Strict-Transport-Security` tells a browser to use HTTPS for the host for a long time. The template's README runs the container on plain HTTP on port 3000, and a header set there would make a localhost or internal hostname unreachable over HTTP until it expires. Setting it only when `TRUST_PROXY` says TLS is terminated upstream keeps it correct in both places.

### Does this change the default template without a custom server?

No. The `default` template runs `react-router-serve`, which has no middleware hook for headers. There the policy would come from the hosting platform or a proxy, and the nonce would need a different path; this pull request is for the `node-custom-server` shape, where `server.js` owns the response.

## More React Router jobs

- [Add a Sitemap to a React Router App](https://getrush.ai/run/add-sitemap/react-router/)
- [Add Structured Logging to a React Router App With a Custom Express Server](https://getrush.ai/run/add-structured-logging/react-router/)
- [Fix "'Switch' is not exported from 'react-router-dom'" after upgrading to React Router 6](https://getrush.ai/run/fix-switch-is-not-exported-from-react-router-dom/react-router/)

## The same job on other stacks

- [Add Security Headers to a Slim 4 App](https://getrush.ai/run/add-security-headers/slim/)
- [Add Security Headers to a SvelteKit App](https://getrush.ai/run/add-security-headers/sveltekit/)
- [Add Security Headers to a Symfony App](https://getrush.ai/run/add-security-headers/symfony/)

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