Beta. consent-kit is at 0.x: expect breaking changes between releases, and treat everything it generates as a draft. Report a problem or share feedback.
Add consent-kit to an existing app
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 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 says which parts stand on their own.
What changes
Section titled “What changes”| Part of the application | Where | What you integrate |
|---|---|---|
| Project root | Build | privacy.registry.yaml, written by hand. Later privacy.lock.json, written by consent-kit release. |
| Build script | Build | consent-kit build, which writes src/consent.gen/, and consent-kit docs, which writes privacy-docs/. |
| Cookie banner | Browser | CookieConsent v3, run with the generated configuration. It replaces the banner you have. |
HTML <head> |
Browser | guard.inline.js, inlined as the first script. Optional. |
| Code that writes cookies or storage | Browser | The generated storage facade, and the ESLint rule that finds raw calls. |
| Third-party scripts and iframes | Browser | Consent-gated tags and placeholders, written from the registry. |
| Server or static host | Hosting | The Content-Security-Policy header from _headers or csp.json. |
| Privacy pages | Hosting | The generated privacy policy and cookie table, published as pages of the site. |
| CI | CI | consent-kit check, build --check, docs --check and consent-kit audit. |
Start the registry
Section titled “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:
npm install --save-dev @consent-kit/cliThere 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:
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.
npx consent-kit checkNo 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 passedDeclare what the app already does
Section titled “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-storagereports every directlocalStorage,sessionStorageanddocument.cookiecall. Step 3 of migrate raw storage calls to the facade shows how to declare each key it reports. -
Third-party tools. Look for a preset in the catalogue and follow add a vendor with a preset. For anything not in it, write the entries by hand.
-
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:
Terminal window npm install --save-dev @consent-kit/auditnpx playwright install chromiumnpx consent-kit audit http://localhost:3000 --page / --page /pricing --check undeclared-driftThe 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 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), or an explicit opt-out with a reason (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.
The fields are explained in the registry model and the registry reference.
Generate the files
Section titled “Generate the files”npx consent-kit buildbuild 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.
npx consent-kit docsdocs 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).
When you deploy for the first time, record the release:
npx consent-kit releaseIt 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.
Change the browser side
Section titled “Change the browser side”Replace the banner
Section titled “Replace the banner”The banner consent-kit configures is 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:
- Remove its script, its markup and its configuration.
- Remove the registry entries you may have pasted for its cookies, and declare
cc_cookieinstead. - Start CookieConsent with the generated configuration:
npm install vanilla-cookieconsent @consent-kit/storageimport * 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
Section titled “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:
<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 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.
Route storage writes through the facade
Section titled “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:
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 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
Section titled “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. Remove the old snippets that load these tools directly.
Hosting
Section titled “Hosting”Send the Content-Security-Policy
Section titled “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): copysrc/consent.gen/_headersinto the deployed output. - Any other server: read
csp.jsonand send itsheaderunder the name inheaderName. Getting started’s serve.mjs does this in two lines;examples/static-site/src/server.tsis 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 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
Section titled “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 describes how the review is recorded. Read documents and phrase review before you publish them.
Endpoints you may need
Section titled “Endpoints you may need”- Consent receipts. With
receipts.endpoint, the banner POSTs one receipt per decision to that path. Deploy the receipt endpoint runs@consent-kit/serveras 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
subjectRequestssection, the form posts to the endpoint you declare; see receive data subject requests.
Check it in CI
Section titled “Check it in CI”Four commands keep the registry, the generated files and the running app in step:
npx consent-kit checknpx consent-kit build --checknpx consent-kit docs --checknpx consent-kit audit http://localhost:3000 --page / --page /pricingcheckfails on an invalid registry and on a change that needs a version bump or a sign-off.build --checkanddocs --checkwrite nothing and fail when the generated files or documents on disk are stale. Passbuild --checkthe same--out,--guard-modeand--report-urlas the build.auditdrives 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 sets up the whole job, including the exercise file for things that only happen after a click.
Adopt it in stages
Section titled “Adopt it in stages”Each stage below works without the ones after it.
- Registry, check and documents. Write the registry, run
check, generate the documents, and runrelease. 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-driftalready works at this stage. - The policy header. Send the generated
Content-Security-Policy, if you like withcsp.reportOnly: truefirst. 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. - 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).
- 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.
- The guard. Build it with
--guard-mode recordfor local runs and audits: it lets undeclared writes through and lists every decision onwindow.__ck_observed. It still blocks a declared artefact that lacks consent. For production,enforce(the default) blocks undeclared writes and reports them to--report-urlif you set one.reportblocks too and differs only in sampling, whichconsent-kit buildcannot set; see guard modes. No mode lets undeclared writes through in production and reports them, so the guard has no observe-only rollout. For loads,csp.reportOnlyis that. - The audit in CI, once the audit passes on your machine.