# Add consent-kit to an existing app

> This guide is for a web app that already runs, and may already have a cookie banner.

This guide is for a web app that already runs, and may already have a cookie banner. It lists what you change, in the order to change it. [Getting started](/docs/manual/getting-started/) builds the same pieces from an empty folder and shows every file in full. Read it next to this guide when you want to see a step end to end.

You do not have to adopt every part at once. [Adopt it in stages](#adopt-it-in-stages) says which parts stand on their own.

> [!WARNING]
> consent-kit is tooling, not legal advice. The documents it writes are drafts, and it cannot tell whether your registry is complete. See [FAQ and compliance notes](/docs/manual/faq/).

## What changes

| Part of the application | Where | What you integrate |
| --- | --- | --- |
| [Project root](#start-the-registry) | Build | `privacy.registry.yaml`, written by hand. Later `privacy.lock.json`, written by `consent-kit release`. |
| [Build script](#generate-the-files) | Build | `consent-kit build`, which writes `src/consent.gen/`, and `consent-kit docs`, which writes `privacy-docs/`. |
| [Cookie banner](#replace-the-banner) | Browser | CookieConsent v3, run with the generated configuration. It replaces the banner you have. |
| [HTML `<head>`](#inline-the-guard) | Browser | `guard.inline.js`, inlined as the first script. Optional. |
| [Code that writes cookies or storage](#route-storage-writes-through-the-facade) | Browser | The generated storage facade, and the ESLint rule that finds raw calls. |
| [Third-party scripts and iframes](#gate-third-party-scripts-and-iframes) | Browser | Consent-gated tags and placeholders, written from the registry. |
| [Server or static host](#send-the-content-security-policy) | Hosting | The `Content-Security-Policy` header from `_headers` or `csp.json`. |
| [Privacy pages](#publish-the-documents) | Hosting | The generated privacy policy and cookie table, published as pages of the site. |
| [CI](#check-it-in-ci) | CI | `consent-kit check`, `build --check`, `docs --check` and `consent-kit audit`. |

## Start the registry

The registry is one file, `privacy.registry.yaml`, at the project root. Every command reads it from the current directory; `--registry <path>` points them elsewhere. The lock, review and documents files are looked for next to it.

Install the CLI:

```sh
npm install --save-dev @consent-kit/cli
```

There is no `init` command. The commands are `check`, `diff`, `build`, `docs`, `release`, `script-tag` and `audit`. Start from a minimal registry that declares only a purpose for running the app, and add to it:

```yaml
version: 1

controller:
  name: My App
  contact: privacy@my-app.example
  address: Example Street 1, 00000 Exampletown
  dpo: false
  supervisoryAuthority:
    name: Example Data Protection Authority
    url: https://dpa.example/complaints

locales: [en]
defaultLocale: en

purposes:
  - id: essential
    version: 1
    basis: legitimate_interest
    title:
      en: Essential
    description:
      en: Runs the application.
    dataCategories: [connection_data]
    retention: 30d
    legitimateInterest:
      en: Delivering the application you asked for.
    automatedDecisionMaking: false
    dataSubjects: [visitors]
    processors: []

processors: []
artefacts: []
collectionPoints: []

dataCategories:
  connection_data: { title: { en: Connection data } }

dataSubjectCategories:
  visitors: { title: { en: Visitors of the website } }

securityMeasures:
  en: Describe how the app protects the data it stores.
```

The controller values are placeholders. Replace them with the real operator of the app.

```sh
npx consent-kit check
```

```
No privacy.lock.json: nothing has been released yet.
The first release will be revision 1. No purpose asks for consent, so no visitor is asked anything.

check passed
```

### Declare what the app already does

The registry has to list every cookie, storage key, third-party script, iframe, pixel, endpoint, stylesheet, font and media file the app uses. Three sources help you find them:

- **Your own code.** The ESLint rule `@consent-kit/no-raw-storage` reports every direct `localStorage`, `sessionStorage` and `document.cookie` call. Step 3 of [migrate raw storage calls to the facade](/docs/manual/guides/migrate-to-the-storage-facade/) shows how to declare each key it reports.
- **Third-party tools.** Look for a preset in the [catalogue](/docs/manual/reference/presets/#catalogue) and follow [add a vendor with a preset](/docs/manual/guides/add-a-vendor-with-a-preset/). For anything not in it, [write the entries by hand](/docs/manual/guides/write-a-registry-entry/).
- **The running app.** The audit's undeclared-drift check loads pages in Chromium and reports every cookie, storage key and third-party request the registry does not declare, each with an entry to paste:

  ```sh
  npm install --save-dev @consent-kit/audit
  npx playwright install chromium
  npx consent-kit audit http://localhost:3000 --page / --page /pricing --check undeclared-drift
  ```

  The URL and pages are your app's. The pasted entries have `purposes: [TODO]`: which purpose each one serves is yours to decide. The audit visits only the pages you list, does not log in, and does not click your current banner, so anything that loads after a click is not in this list. The [audit reference](/docs/manual/reference/audit/#limits) lists what else it cannot see.

Anything optional, such as analytics or an embedded video, goes under a purpose with `basis: consent`. As soon as the registry has one, it also needs a `receipts` section: an endpoint that stores proof of each decision ([deploy the receipt endpoint](/docs/manual/guides/deploy-the-receipt-endpoint/)), or an explicit opt-out with a reason ([opt out of receipts](/docs/manual/guides/opt-out-of-receipts/)). Without it the registry does not validate (`receipts/not-stated`). Declare the banner's own cookie, `cc_cookie`, under your essential purpose, as Getting started does in [its registry](/docs/manual/getting-started/#2-write-the-registry).

The fields are explained in [the registry model](/docs/manual/concepts/registry-model/) and the [registry reference](/docs/manual/reference/registry/).

## Generate the files

```sh
npx consent-kit build
```

`build` runs the check first and refuses to write anything if it fails. It writes to `src/consent.gen/`, or to the directory given with `--out`:

| File | Used by |
| --- | --- |
| `cookieconsent.config.gen.ts` | Your browser code: the banner configuration. |
| `storage.gen.ts` | Your browser code: the typed storage facade. |
| `registry.gen.ts` | Your code: the registry's ids as TypeScript types. |
| `guard.inline.js` | Your HTML: the runtime guard. |
| `_headers`, `csp.json` | Your host or server: the Content-Security-Policy. |
| `guard-manifest.json`, `policy.json` | The audit and other tools. |
| `receipts.manifest.gen.json` | Your receipt endpoint. Only with `receipts.endpoint`. |

With a `subjectRequests` section, `build` also writes the request form and its manifest. Every file is described in [generated files](/docs/manual/reference/generated-files/).

```sh
npx consent-kit docs
```

`docs` writes the privacy policy, the cookie table, the record of processing activities, the processor list and the field notices to `privacy-docs/`, or to `--out`. They are drafts. Each Markdown document carries an "Unreviewed draft" banner until a lawyer's review of its phrases is on record.

Run both from the build you already have, before the bundler. The documentation site runs `consent-kit check` as the first step of `npm run build`; the demo app's build script is `consent-kit check && node scripts/build.mjs`. Commit the generated files or generate them in every build; either works, as long as CI checks them ([below](#check-it-in-ci)).

When you deploy for the first time, record the release:

```sh
npx consent-kit release
```

It writes `privacy.lock.json`. Commit it. From then on `check` compares every change to the registry with it and says whether visitors have to be asked again; see [release a policy change](/docs/manual/guides/release-a-policy-change/).

## Change the browser side

### Replace the banner

The banner consent-kit configures is [CookieConsent](https://github.com/orestbida/cookieconsent) v3, the npm package `vanilla-cookieconsent`. The other parts depend on it: the guard and the storage facade read the visitor's choice from its cookie, `cc_cookie`, and the audit clicks its markup. Another banner's choice is not read by any of them. So the banner you have goes:

1. Remove its script, its markup and its configuration.
2. Remove the registry entries you may have pasted for its cookies, and declare `cc_cookie` instead.
3. Start CookieConsent with the generated configuration:

```sh
npm install vanilla-cookieconsent @consent-kit/storage
```

```ts
import * as CookieConsent from 'vanilla-cookieconsent';
import { cookieConsentConfig } from './consent.gen/cookieconsent.config.gen.ts';

void CookieConsent.run({ ...cookieConsentConfig });
```

`@consent-kit/storage` is imported by the storage facade, and by the generated configuration when the registry declares `receipts.endpoint`, to send receipts. Serve `vanilla-cookieconsent/dist/cookieconsent.css` from your own origin; the strict policy refuses a stylesheet from a CDN. Put a link that reopens the preferences in the footer of every page, `<button type="button" data-cc="show-preferencesModal">Privacy preferences</button>`; the audit checks that it is there.

Choices made in the old banner are not carried over. Every visitor is asked once, by the new banner.

If no purpose in the registry has `basis: consent`, the app needs no banner. Remove the old one and do not add CookieConsent. The audit then fails any page that still shows a banner (`banner-without-consent`), because it would ask for a consent nothing needs.

### Inline the guard

`guard.inline.js` patches `document.cookie`, the storage APIs and script and iframe insertion, and lets through only what the registry declares and the visitor consented to. Inline it as the first script in `<head>` of every page, byte for byte:

```html
<head>
  <meta charset="utf-8" />
  <script>/* the contents of src/consent.gen/guard.inline.js */</script>
  …
</head>
```

The policy in `_headers` and `csp.json` allows it by the hash of its exact text. A formatter or HTML minifier that changes one byte makes the browser refuse it without an error. Getting started's [build script](/docs/manual/getting-started/#7-build-the-site) replaces a marker comment with the file's text; the demo app does the same in `demo/scripts/build.mjs`.

The guard is optional. The other layers work without it, and the audit does not report a page that has none. Which mode to build it in is covered in [adopt it in stages](#adopt-it-in-stages).

### Route storage writes through the facade

Every write your code makes to cookies, localStorage or sessionStorage goes through the generated facade, which refuses a write the visitor has not consented to and does not compile for an undeclared key:

```ts
import { cookieConsentAccepted } from '@consent-kit/storage';
import { createProjectStorage } from './consent.gen/storage.gen.ts';

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

In an existing codebase this is the largest change. [Migrate raw storage calls to the facade](/docs/manual/guides/migrate-to-the-storage-facade/) does it one lint report at a time, including the clean-up after a withdrawal (`storage.clearUnconsented()` in CookieConsent's `onChange`).

### Gate third-party scripts and iframes

A script bound to a consent purpose is written as a tag the browser does not run until CookieConsent activates it. Print it with `npx consent-kit script-tag <artefact-id>`, or write it in your build with `consentScriptTag` from `@consent-kit/cli`. An iframe gets a placeholder from `consentEmbed` at build time and is swapped in by `syncEmbeds` in the browser; see [embed an iframe behind consent](/docs/manual/guides/embed-an-iframe/). Remove the old snippets that load these tools directly.

## Hosting

### Send the Content-Security-Policy

The policy only takes effect when the server sends it as a response header.

- A host that reads `_headers` (Netlify and Cloudflare Pages format): copy `src/consent.gen/_headers` into the deployed output.
- Any other server: read `csp.json` and send its `header` under the name in `headerName`. Getting started's [serve.mjs](/docs/manual/getting-started/#8-serve-it-with-the-policy) does this in two lines; `examples/static-site/src/server.ts` is another.

The generated policy is strict: no inline script except the guard, no inline style, and no origin the registry does not declare. Expect an existing app to break under it at first. The usual fixes are to declare what is missing and to move inline code into files; [loosen the CSP](/docs/manual/guides/loosen-the-csp/) covers what is left, and how to start with `csp.reportOnly: true`, which reports violations without blocking anything. The policy also sets `frame-ancestors 'none'`; if another site of yours frames the app, allow that origin there, as the demo app does for the landing page.

If your framework writes inline scripts into the pages it builds, give the policy their hashes. consent-kit's documentation site is an Astro / Starlight site and does exactly this: after `astro build`, `website/scripts/csp.mjs` hashes every inline script in the built HTML, calls `contentSecurityPolicy(registry, { inlineScriptHashes })` from `@consent-kit/cli`, and writes the header into the site's `dist/_headers`. Its registry loosens `style-src` and `img-src`, each with a reason, because Starlight sets style attributes and draws icons from `data:` URLs. That is the one framework setup in this repository; other frameworks are not covered by an example.

### Publish the documents

`consent-kit docs` writes files; it does not serve them. Publish the Markdown documents as pages of your app the way you publish any other content, and link to them from the app. The JSON and CSV files carry the same content for a page you render yourself or for your records.

Each document stays stamped as an unreviewed draft until its phrases are reviewed. [Record a lawyer's review](/docs/manual/guides/record-a-legal-review/) describes how the review is recorded. Read [documents and phrase review](/docs/manual/concepts/documents-and-phrase-review/) before you publish them.

### Endpoints you may need

- **Consent receipts.** With `receipts.endpoint`, the banner POSTs one receipt per decision to that path. [Deploy the receipt endpoint](/docs/manual/guides/deploy-the-receipt-endpoint/) runs `@consent-kit/server` as a Cloudflare Worker.
- **Guard reports.** With `--report-url`, the guard sends a beacon for every undeclared write it blocks. consent-kit ships no receiver for these.
- **Subject requests.** With a `subjectRequests` section, the form posts to the endpoint you declare; see [receive data subject requests](/docs/manual/guides/receive-data-subject-requests/).

## Check it in CI

Four commands keep the registry, the generated files and the running app in step:

```sh
npx consent-kit check
npx consent-kit build --check
npx consent-kit docs --check
npx consent-kit audit http://localhost:3000 --page / --page /pricing
```

- `check` fails on an invalid registry and on a change that needs a version bump or a sign-off.
- `build --check` and `docs --check` write nothing and fail when the generated files or documents on disk are stale. Pass `build --check` the same `--out`, `--guard-mode` and `--report-url` as the build.
- `audit` drives the running app in Chromium and fails when it does something the registry does not declare, or does it before consent.

Audit a build whose guard is in `record` mode, served with the policy header it was built with. In `enforce` mode the guard blocks an undeclared write before the audit can see it. [Run the audit in CI](/docs/manual/guides/run-the-audit-in-ci/) sets up the whole job, including the exercise file for things that only happen after a click.

## Adopt it in stages

Each stage below works without the ones after it.

1. **Registry, check and documents.** Write the registry, run `check`, generate the documents, and run `release`. Nothing in the app changes. You get an inventory that is checked on every change, and draft documents that match it. The audit with `--check undeclared-drift` already works at this stage.
2. **The policy header.** Send the generated `Content-Security-Policy`, if you like with `csp.reportOnly: true` first. consent-kit's own documentation site stops here: it declares nothing that needs consent, has no banner and no guard, and sends only the policy.
3. **No banner, if nothing needs consent.** A registry without a consent purpose needs no banner. Remove the old one; the audit adapts its checks to a site that asks for nothing ([sites that ask for no consent](/docs/manual/reference/audit/#sites-that-ask-for-no-consent)).
4. **The banner, the facade and the gated tags**, once a purpose rests on consent. These belong together: the banner records the choice, and the facade and the tags act on it.
5. **The guard.** Build it with `--guard-mode record` for local runs and audits: it lets undeclared writes through and lists every decision on `window.__ck_observed`. It still blocks a declared artefact that lacks consent. For production, `enforce` (the default) blocks undeclared writes and reports them to `--report-url` if you set one. `report` blocks too and differs only in sampling, which `consent-kit build` cannot set; see [guard modes](/docs/manual/reference/runtime-api/#modes). No mode lets undeclared writes through in production and reports them, so the guard has no observe-only rollout. For loads, `csp.reportOnly` is that.
6. **The audit in CI**, once the audit passes on your machine.

## Related

- [Getting started](/docs/manual/getting-started/)
- [How consent flows at runtime](/docs/manual/concepts/runtime-consent-flow/)
- [CLI reference](/docs/manual/reference/cli/)
- [Generated files](/docs/manual/reference/generated-files/)
- [Threat model and known limits](/docs/manual/concepts/threat-model-and-limits/)
