# How consent flows at runtime

> What happens in a visitor's browser: how the banner records a choice, which generated piece acts on it, and why the Content-Security-Policy, not the JavaScript, is the boundary that counts.

What happens in a visitor's browser: how the banner records a choice, which generated piece acts on it, and why the Content-Security-Policy, not the JavaScript, is the boundary that counts.

## The layers

Five things generated from the registry are active on a page. They overlap on purpose.

| Layer | Runs | What it does | What it depends on |
| --- | --- | --- | --- |
| Content-Security-Policy | In the browser engine, before any code | Refuses every load and connection to an origin the registry does not declare | The response header |
| Inline guard | First script in `<head>` | Checks cookie, storage, script and iframe writes against the registry and the current consent | Running before everything else |
| CookieConsent | Your bundle | Shows the banner, stores the choice in the `cc_cookie` cookie, activates blocked script tags, erases cookies on withdrawal | The generated configuration |
| Storage facade | Your code | The only way your code writes cookies and storage; refuses without consent | Your code using it (the ESLint rule) |
| Embed placeholders | Your HTML and bundle | Stand in for an iframe until the visitor agrees | `consentEmbed` at build time, `syncEmbeds` in the browser |

```mermaid
sequenceDiagram
  participant V as Visitor
  participant B as Browser (CSP)
  participant G as Inline guard
  participant C as CookieConsent
  participant S as Site code
  B->>G: page starts, guard installs first
  S->>G: write cookie or storage, insert script or iframe
  G-->>S: allowed only if declared and consented
  C->>V: banner (no stored choice)
  V->>C: accept analytics
  C->>C: write cc_cookie
  C->>B: activate script tags of the category
  C->>S: onConsent / onChange
  S->>S: syncEmbeds, clearUnconsented
  C-->>S: cc:onFirstConsent (receipt is sent)
```

## Where the choice lives

The visitor's choice lives in one place: CookieConsent's cookie, `cc_cookie`. It holds the accepted categories (your consent purpose ids), the accepted services per category (your processor ids), the revision, and a random `consentId`.

Every layer reads that cookie fresh on every check. Nothing caches consent, so a withdrawal takes effect at the next call. Every reader fails closed: a missing or garbled cookie means nothing is accepted.

An artefact is consented when all of its consent purposes are accepted categories and, if it has a processor, that processor's service is accepted in each of them. An artefact with no consent purpose is always allowed.

## The banner

The generated configuration sets CookieConsent to opt-in mode with every consent category off, "Accept all" and "Reject all" given equal weight, and Global Privacy Control respected. Purposes on other bases get no toggle.

The configuration carries the revision. When the revision in a visitor's cookie does not match the one in the configuration, CookieConsent shows the banner again. That is the whole re-consent mechanism at runtime; deciding when the revision goes up is the subject of [material changes and re-consent](/docs/manual/concepts/material-changes/).

## Scripts

A script bound to a consent purpose is written into the page in a form the browser does not run:

```html
<script type="text/plain" data-category="analytics" data-service="plausible" data-src="https://plausible.io/js/script.js"></script>
```

When the visitor accepts the category and service, CookieConsent turns it into a real script. `consentScriptTag` (or `consent-kit script-tag`) writes the tag from the registry, so the category and service can never disagree with the banner.

A script that has run cannot be unloaded. On withdrawal the example site reloads the page.

## Cookies and storage

Your own code goes through the generated facade:

```ts
const storage = createProjectStorage<{ theme: 'light' | 'dark' }>(cookieConsentAccepted());
storage.local.set('theme', 'dark');
```

A key that the registry does not declare is a compile error. A write without the consent the key needs is refused and returns `{ ok: false, reason: 'not_consented' }`. The facade never throws. Reads and removals are not gated.

On withdrawal, CookieConsent erases the cookies of the category. It cannot erase localStorage, sessionStorage or IndexedDB, so your `onChange` handler calls `storage.clearUnconsented()`, which removes every declared entry that is no longer consented.

The ESLint rule `@consent-kit/no-raw-storage` keeps code from bypassing the facade with `localStorage.setItem` or `document.cookie`.

## Iframes

`consentEmbed` writes a placeholder instead of an iframe. `syncEmbeds`, called from CookieConsent's `onConsent` and `onChange`, swaps the placeholder for the iframe once the category is accepted, and back on withdrawal. See [embed an iframe behind consent](/docs/manual/guides/embed-an-iframe/).

## The guard

The facade and the script tags only govern code that uses them. A third-party script does not. The guard is the backstop: an inline script, first in `<head>`, that patches the browser's own APIs before anything else runs.

It intercepts, in the top-level document:

- cookie writes (`document.cookie`, `cookieStore.set`);
- `localStorage` and `sessionStorage` writes through `setItem`;
- `indexedDB.open`;
- `<script src>` and `<iframe src>` elements as they are inserted or changed.

What it does with a write depends on its mode:

| Situation | `enforce` (the CLI default) | `report` | `record` | `throw` |
| --- | --- | --- | --- | --- |
| Not declared in the registry | Blocked, reported | Blocked, reported if sampled | Allowed, recorded | Throws |
| Declared, consent missing | Blocked | Blocked | Blocked | Throws |

`record` is the mode to audit in: it lets undeclared writes through so the audit can see what they would have done. `throw` is for development. Deleting a cookie or a key always passes. Same-origin scripts and iframes that no entry matches are first-party code and are allowed.

The guard also knows about `fetch`, `XMLHttpRequest` and `sendBeacon`, but only to label requests as declared or undeclared for the audit. It never blocks a request.

## Why the CSP is the real boundary

The guard is JavaScript running in the same page as the code it polices. It is honest about what that means:

- It does not see reads.
- It does not see `localStorage.foo = 'x'`; only `setItem`.
- A script can take an unpatched API from a fresh iframe.
- `Set-Cookie` response headers and HttpOnly cookies never pass through `document.cookie`.
- It notices an inserted script after insertion. For a parser-inserted script it reliably stops execution; for a dynamically inserted one the request may already have started.
- It has no hook at all for `<link>`, CSS `url()`, `<img>` or `<video>`.

The Content-Security-Policy has none of these gaps. The browser engine enforces it before any script runs, and page code cannot switch it off. It starts from `default-src 'none'` and admits, per resource type, only the site's own origin and the origins the registry declares. A script from an undeclared origin is not fetched. A beacon to an undeclared origin is not sent.

So the two layers answer different questions:

| | Content-Security-Policy | Guard, facade, banner |
| --- | --- | --- |
| Question | Is this origin declared at all? | Is this declared thing consented right now? |
| Changes with consent | No. The header is the same before and after. | Yes. |
| Granularity | Origin | Declared path, cookie name, storage key |
| Can page code bypass it | No | In the ways listed above |

The policy is the outer wall: nothing undeclared gets in or out. Inside the wall, the gates decide what waits for consent. That is why a stylesheet, font or media file cannot be bound to a consent purpose: there is a wall for it but no gate.

It is also why the policy is strict by default and every loosening is written in the registry with a reason. An `'unsafe-inline'` in `script-src` would let any injected markup run script, and the wall would be gone.

> [!WARNING]
> The policy only protects a page that is served with it. `consent-kit build` writes the header to `_headers` and `csp.json`; delivering it is your host's or server's job. The audit computes the policy from the registry and does not prove that your server sent it.

## The inline guard and its hash

The policy forbids inline scripts, and the guard is an inline script. The build resolves this by putting the SHA-256 hash of `guard.inline.js` into `script-src`. The consequence is strict: the guard must be inlined byte for byte, including its trailing newline. If a templating step or a minifier changes one character, the browser silently refuses the script and the page runs without a guard. The audit's "runtime guard installed" check exists to catch exactly that.

## What happens on each event

| Event | What acts |
| --- | --- |
| First page view, no choice yet | The policy refuses undeclared origins. The guard blocks unconsented writes. Blocked script tags stay inert. Placeholders stand in for iframes. The banner is shown. |
| Visitor accepts a category | CookieConsent writes `cc_cookie` and activates the category's script tags. `onConsent` runs `syncEmbeds`. The guard and facade now let that category's artefacts through. A receipt with `event: "first"` is sent. |
| Visitor rejects everything | CookieConsent writes `cc_cookie` with no optional category. Nothing else changes. A receipt is sent for the rejection too. |
| Visitor changes the choice | CookieConsent erases the cookies of withdrawn categories. `onChange` runs `clearUnconsented()` and `syncEmbeds`. A receipt with `event: "change"` is sent. Reload if something was withdrawn. |
| Visitor sends the GPC signal | CookieConsent treats them as having refused. See [Global Privacy Control](/docs/manual/concepts/global-privacy-control/). |
| The revision goes up | CookieConsent shows the banner again to every visitor whose cookie carries an earlier revision. |

## Next

- [Runtime API reference](/docs/manual/reference/runtime-api/): every option and method.
- [The threat model and known limits](/docs/manual/concepts/threat-model-and-limits/): what none of the layers stops.
- [Content-Security-Policy reference](/docs/manual/reference/content-security-policy/).
