# Content Security Policy

> A strict policy on every page, with the engine allowing its own inline code by hash or nonce.

A Content-Security-Policy that refuses inline scripts stops injected markup
from turning into injected code. Turn it on in the plugin, and the engine
allows the inline code each page needs, by hash or by nonce:

```ts title="vite.config.ts"
rscKit({
  contentSecurityPolicy: {},
})
```

That is a strict policy on every page, with no `'unsafe-inline'` for scripts.

## Turning it on

`{}` sends this default:

```text
default-src 'self'; base-uri 'self'; object-src 'none'; style-src-attr 'unsafe-inline'
```

Every page then adds a `script-src` and a `style-src` naming its own inline
code: the script that boots it, and the scripts React writes to put each
streamed part in place.

## Adding to the default

`extend` adds sources to the default and keeps the rest of it. This allows
Cloudflare Turnstile, which loads a script and opens a frame:

```ts title="vite.config.ts"
rscKit({
  contentSecurityPolicy: {
    extend: {
      'script-src': 'https://challenges.cloudflare.com',
      'frame-src': 'https://challenges.cloudflare.com',
    },
  },
})
```

```text
default-src 'self'; base-uri 'self'; object-src 'none'; style-src-attr 'unsafe-inline'; script-src 'self' https://challenges.cloudflare.com; frame-src 'self' https://challenges.cloudflare.com
```

A directive takes a list or a space-separated string:

```ts
'img-src': ['data:', 'https://images.example.com'],
'img-src': 'data: https://images.example.com',
```

- **A directive the default doesn't name** starts from the one the browser
  would fall back to. `script-src` starts from `default-src 'self'`, so adding
  an origin never blocks your own scripts.
- **One that falls back to nothing**, such as `frame-ancestors` or
  `form-action`, is only what you write.
- **A source added to a `'none'` directive** replaces the `'none'`.

`extend` only adds. Closing a directive that allows something, as in
`'frame-src': "'none'"`, fails the build: write that policy with `directives`.

## Writing the whole policy

`directives` replaces the default, so a directive you leave out isn't sent.
Setting both `extend` and `directives` fails the build.

```ts title="vite.config.ts"
rscKit({
  contentSecurityPolicy: {
    directives: {
      'default-src': ["'self'"],
      'img-src': ["'self'", 'data:', 'https://images.example.com'],
      'connect-src': ["'self'", 'https://api.example.com'],
      'frame-ancestors': ["'none'"],
      'base-uri': ["'self'"],
      'object-src': ["'none'"],
      'style-src-attr': ["'unsafe-inline'"],
    },
  },
})
```

Keep `style-src-attr 'unsafe-inline'`. React's `style={{ ... }}` is a style
attribute, which no hash or nonce can allow. An attribute can't run code, and
without it every `style` prop is refused.

A directive that already has `'unsafe-inline'` is left as you wrote it, since
a hash or nonce beside it would switch it off. A policy with no `script-src`
and no `default-src` restricts no scripts, and isn't given one.

## Trying it before enforcing it

```ts title="vite.config.ts"
rscKit({
  contentSecurityPolicy: { reportOnly: true },
})
```

The policy goes out as `Content-Security-Policy-Report-Only`, so the browser
reports what it would refuse and runs it anyway.

## Your own inline code

The engine allows the inline code it writes. For inline code you write:

- **A `<script>` or `<style>` in a page the build stores**, a shell included,
  is hashed with everything else, and runs.
- **One inside a Suspense hole, or on a page rendered per request**, is
  refused: React gives a nonce to the scripts it writes, not to the elements
  you render — unless you give it one, with
  [`useNonce()`](#a-library-that-asks-for-a-nonce).
- **One brought by a navigation** is refused on every page: the browser
  inserts it into a document whose policy was decided before it existed.

A stored page is hashed as it was written, whoever wrote it. If the page
prints HTML that came from someone else, such as a comment or a CMS field
through `dangerouslySetInnerHTML`, a `<script>` in that HTML is hashed and
allowed like your own. The policy does not protect a stored or kept page from
markup you put there, so sanitize that HTML before rendering it. A page
rendered per request has no such gap: only a script with the nonce runs.

So write CSS in a stylesheet and code in a module, which `'self'` allows:

```tsx title="src/app/layout.tsx"
import './styles.css';

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <body>
        {children}
        <script type="module" src="/analytics.js" />
      </body>
    </html>
  );
}
```

[Third-party scripts](/guides/third-party-scripts) loaded by `src` need their
origin in `script-src`:

```ts
extend: { 'script-src': 'https://plausible.io' },
```

If your app writes `<style>` tags, put `'unsafe-inline'` in `style-src` and
the engine leaves it alone.

### A library that asks for a nonce

Some libraries write inline code and take a `nonce` for it: next-themes'
script that sets the theme before the page paints, and the `<style>` its
`disableTransitionOnChange` inserts on every theme change; an analytics
snippet; a CSS-in-JS runtime. `useNonce()` is the nonce to give them:

```tsx title="src/app/Theme.tsx"
'use client';

import { ThemeProvider } from 'next-themes';
import { useNonce } from '@rsc-kit/core/useNonce';
import type { ReactNode } from 'react';

export function Theme({ children }: { children: ReactNode }) {
  const nonce = useNonce();

  return (
    <ThemeProvider attribute="class" defaultTheme="system" enableSystem disableTransitionOnChange nonce={nonce}>
      {children}
    </ThemeProvider>
  );
}
```

Render `<Theme>` from the root layout in place of the `ThemeProvider`.

It is a client hook because the nonce that counts is the document's. A
navigation's payload is rendered with a nonce of its own, which the page on
screen has never seen, so a nonce read on the server and passed down as a prop
would be wrong after the first navigation. On the server it is the nonce the
response is written with; in the browser it is read back from the document.

It is `undefined` on a page allowed by hash: a stored page, a shell's own
HTML, one a cache keeps. That is fine for what is in the HTML, because the
library's inline script is hashed with the rest of the page. What a library
inserts after hydration on such a page has nothing to run by, unless the page
has holes, whose nonce it then uses. On a stored page with none, put
`'unsafe-inline'` in `style-src` if the library inserts styles, or leave the
option off — next-themes works without `disableTransitionOnChange`.

The engine's own components use it too: `PageTransition`'s style, inserted
by React in the browser when it wasn't in the HTML, as in `vite dev`, carries
the nonce.

## Setting it from a middleware

Don't. A middleware that sets its own `Content-Security-Policy` keeps it, and
the engine adds nothing to it, so React never learns a nonce and every
streamed page is refused. `contentSecurityPolicy` and a
`Content-Security-Policy` in [`headers`](/guides/response-headers) are the
same header twice, so the build refuses both together.

## In development

**`vite dev`** sends the same policy, so what production would refuse is
refused while you work. It adds:

- `'unsafe-eval'` in `script-src`, which React's development build needs;
- the local dev server in `connect-src` (`ws://localhost:*` and
  `127.0.0.1`, where Vite's HMR client goes when the page is served from
  `my-app.test`).

None of these is ever in a build. Every page renders per request in dev, so
every page is allowed by its nonce, and Vite's own inline styles (a CSS
update, the error overlay) carry it too. Your own inline `<script>` or
`<style>` is refused in dev even on a page the build would store and hash.

## Where it is sent

- **A server, anywhere**: Node, Bun, Docker, a Worker, a function. The host
  sets the header on each page, and nothing depends on the platform.
- **An edge cache** that implements the
  [edge contract](/reference/edge-contract) sends a stored page's policy with
  its copy. A shell goes only to an edge that makes a nonce for each
  response (`nonceShells`), which it puts in the policy and sends to your app
  for the holes. An edge that can't leaves those pages to your app.
- **A static export** has no server to send a header, so each page carries its
  policy as a `<meta http-equiv="Content-Security-Policy">` with its own
  hashes. A `<meta>` can't carry `frame-ancestors`, `report-uri`,
  `report-to` or `sandbox`, and can't be report-only; set those as headers
  on the host if it can.

## How it works

How a page's inline code is allowed depends on whether its body is whole
before its headers leave.

| The page | Allowed by | Why |
| --- | --- | --- |
| Stored at build | the hash of each inline script and style in it | the same bytes for everyone, so one header for everyone, and caches keep sharing it |
| [Kept](/guides/isr) by `revalidate` | the same, from the body that is kept | rendered with no nonce, because the copy is shared |
| A [shell](/guides/ppr) with its holes resumed | the shell's hashes, and a nonce for the holes | the holes are rendered for this request |
| Rendered per request | a nonce | it streams: its last script isn't known when the header goes |

A nonce is 128 random bits, new for every response, and is only ever put on a
response no cache may share. React puts it on every script it writes, and on
the styles it hoists.

The payload a page hydrates from isn't code. It travels in the page as
`<script type="application/json">` data blocks, which a browser never runs and
a policy never judges, so a page's data needs nothing allowed.
