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.
Getting started
A tutorial that takes a small static site from an empty folder to a passing browser audit and a first release. It takes about half an hour.
Adding consent-kit to an app you already have? See add consent-kit to an existing app.
You will build “Trip Notes”: two pages, a consent banner, and one optional feature that needs consent. The feature remembers the page a visitor opened last and offers a link back to it. The site has no third-party vendor, so everything runs on your machine.
By the end you will have:
- a
privacy.registry.yamlthat declares what the site stores and why; - a CookieConsent banner, a strict Content-Security-Policy, an inline guard and a typed storage module, all generated from that file;
- an audit in a real browser that passes, and that fails when you break the declaration;
- a first release recorded in
privacy.lock.json.
Before you start
Section titled “Before you start”You need Node.js 22 or newer and a terminal.
1. Create the project
Section titled “1. Create the project”mkdir trip-notes && cd trip-notesnpm init -ynpm pkg set type=modulenpm install vanilla-cookieconsent @consent-kit/storagenpm install --save-dev @consent-kit/cli @consent-kit/audit esbuildnpx playwright install chromium| Package | Why |
|---|---|
@consent-kit/cli |
The command line tool (the consent-kit command). |
vanilla-cookieconsent |
The banner. consent-kit generates its configuration. |
@consent-kit/storage |
The storage facade that the generated modules import. It ends up in your browser bundle. |
@consent-kit/audit |
The browser audit. It brings Playwright, so it is a separate, optional package. |
esbuild |
Bundles the browser code. Any bundler that handles TypeScript works. |
2. Write the registry
Section titled “2. Write the registry”Create privacy.registry.yaml. It is the only privacy file you write by hand.
version: 1
controller: name: Trip Notes contact: privacy@trip-notes.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: Remembers your privacy choices so we do not ask again on every page. dataCategories: [consent_choices] retention: 182d legitimateInterest: en: Keeping a record of your privacy choices so that we can honour them. automatedDecisionMaking: false dataSubjects: [visitors] processors: []
- id: reading_position version: 1 basis: consent default: denied title: en: Continue reading description: en: Remembers in this browser which page of the site you opened last, to offer a link back to it on your next visit. dataCategories: [reading_history] retention: until-withdrawn automatedDecisionMaking: false dataSubjects: [visitors] processors: []
processors: []
artefacts: - id: cc_cookie kind: cookie name: cc_cookie duration: 182d sameSite: Lax purposes: [essential] description: en: Stores your privacy choices.
- id: last_page kind: storage area: local key: last_page duration: persistent purposes: [reading_position] description: en: The page you opened last.
collectionPoints: []
dataCategories: consent_choices: { title: { en: Your privacy choices } } reading_history: { title: { en: The page you opened last } }
dataSubjectCategories: visitors: { title: { en: Visitors of the website } }
securityMeasures: en: The site is static. No personal data is stored on the server.
receipts: endpoint: /consent-receiptsWhat you just declared:
- Two purposes.
essentialrests on a legitimate interest and has no toggle.reading_positionrests on consent: it is off until the visitor agrees. - Two artefacts.
cc_cookieis the cookie the banner stores the choice in.last_pageis a localStorage key bound to the consent purpose, so nothing may write it before consent. - Where proof of each decision goes. A registry that asks for consent has to say so. Here the site will answer
POST /consent-receiptsitself.
The controller, its address and the authority are example values. The fields are explained in the registry model.
3. Check it
Section titled “3. Check it”npx consent-kit checkNo privacy.lock.json: nothing has been released yet.The first release will be revision 1; every visitor is asked for the first time.
check passedTo see what a validation error looks like, delete the receipts section and run the check again. It fails with receipts/not-stated and tells you what to add. Put the section back.
4. Generate the files
Section titled “4. Generate the files”npx consent-kit build --guard-mode recordcreated src/consent.gen/_headerscreated src/consent.gen/cookieconsent.config.gen.tscreated src/consent.gen/csp.jsoncreated src/consent.gen/guard-manifest.jsoncreated src/consent.gen/guard.inline.jscreated src/consent.gen/policy.jsoncreated src/consent.gen/receipts.manifest.gen.jsoncreated src/consent.gen/registry.gen.tscreated src/consent.gen/storage.gen.ts
Built revision 1 with guard mode "record": 9 written, 0 unchanged.Revision 1: every visitor is asked for the first time.--guard-mode record builds the guard in the mode meant for auditing: it lets undeclared writes through and records them, so the audit can see them. The default mode, enforce, blocks them silently. You will switch to it in the last step.
Each file is described in generated files. You will use four of them: the banner configuration, the storage module, the inline guard and the policy.
5. Write the browser code
Section titled “5. Write the browser code”Create src/main.ts:
import * as CookieConsent from 'vanilla-cookieconsent';import { cookieConsentAccepted } from '@consent-kit/storage';import { cookieConsentConfig } from './consent.gen/cookieconsent.config.gen.ts';import { createProjectStorage } from './consent.gen/storage.gen.ts';
const isString = (value: unknown): value is string => typeof value === 'string';
// Keys are checked against the registry when this compiles; consent is checked at every call.const storage = createProjectStorage<{ last_page: string }>(cookieConsentAccepted());
// Read the page the visitor opened last, before this page overwrites it.const lastPage = storage.local.get('last_page', isString);const hint = document.getElementById('continue');const link = hint?.querySelector('a');if (hint && link && lastPage !== undefined && lastPage !== location.pathname) { link.href = lastPage; link.textContent = lastPage; hint.hidden = false;}
// Refused, without an error, until the visitor accepts "Continue reading".const rememberPage = () => storage.local.set('last_page', location.pathname);
void CookieConsent.run({ ...cookieConsentConfig, onConsent: rememberPage, onChange: () => { // CookieConsent erases cookies on withdrawal; localStorage is ours to clear. storage.clearUnconsented(); rememberPage(); },});Three things to notice:
- The code never touches
localStoragedirectly.storage.local.set('last_page', …)writes only when the visitor has acceptedreading_position; otherwise it returns{ ok: false, reason: 'not_consented' }and does nothing. - A key that is not in the registry, such as
storage.local.set('visits', 1), does not compile. - Importing the generated configuration is all it takes to send consent receipts.
6. Write the pages
Section titled “6. Write the pages”Create pages/index.html:
<!doctype html><html lang="en"> <head> <meta charset="utf-8" /> <!-- consent-kit:guard --> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>Trip Notes</title> <link rel="stylesheet" href="/assets/cookieconsent.css" /> <script src="/assets/site.js" defer></script> </head> <body> <main> <h1>Trip Notes</h1> <p><a href="/lisbon.html">Three days in Lisbon</a></p> <p id="continue" hidden>Continue reading: <a></a></p> </main> <footer> <button type="button" data-cc="show-preferencesModal">Privacy preferences</button> </footer> </body></html>Create pages/lisbon.html as a copy with another title and body:
<!doctype html><html lang="en"> <head> <meta charset="utf-8" /> <!-- consent-kit:guard --> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>Three days in Lisbon</title> <link rel="stylesheet" href="/assets/cookieconsent.css" /> <script src="/assets/site.js" defer></script> </head> <body> <main> <h1>Three days in Lisbon</h1> <p>Day one: the tram to Belém. <a href="/">Back to all notes</a></p> <p id="continue" hidden>Continue reading: <a></a></p> </main> <footer> <button type="button" data-cc="show-preferencesModal">Privacy preferences</button> </footer> </body></html>- The comment
<!-- consent-kit:guard -->is a marker of this tutorial’s own build script, which replaces it with the guard. It sits before every other script. - There is no inline script and no inline style. The policy would refuse them.
- The footer button reopens the preferences. A visitor must be able to change their mind as easily as they made it up, and the audit checks that the link exists.
7. Build the site
Section titled “7. Build the site”Create build.mjs:
import { copyFileSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';import { buildSync } from 'esbuild';
const gen = 'src/consent.gen';rmSync('dist', { recursive: true, force: true });mkdirSync('dist/assets', { recursive: true });
// 1. One browser bundle: CookieConsent, the generated modules and the storage facade.buildSync({ entryPoints: ['src/main.ts'], outfile: 'dist/assets/site.js', bundle: true, format: 'iife', target: 'es2020' });
// 2. CookieConsent's stylesheet, served by the site itself so that style-src 'self' admits it.copyFileSync('node_modules/vanilla-cookieconsent/dist/cookieconsent.css', 'dist/assets/cookieconsent.css');
// 3. The pages, with the guard inlined byte for byte: the policy allows it by the hash of this exact text.const guard = readFileSync(`${gen}/guard.inline.js`, 'utf8');for (const name of readdirSync('pages')) { const page = readFileSync(`pages/${name}`, 'utf8'); writeFileSync(`dist/${name}`, page.replace('<!-- consent-kit:guard -->', () => `<script>${guard}</script>`));}
// 4. The Content-Security-Policy, for a host that reads _headers.copyFileSync(`${gen}/_headers`, 'dist/_headers');node build.mjs8. Serve it with the policy
Section titled “8. Serve it with the policy”The Content-Security-Policy only does something when the server sends it. A plain static file server would not. Create serve.mjs:
import { createServer } from 'node:http';import { existsSync, readFileSync } from 'node:fs';import { extname, join, normalize } from 'node:path';
const types = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8' };
createServer((request, response) => { const { pathname } = new URL(request.url, 'http://localhost'); // Every response carries the generated policy. Read per request, so a rebuild needs no restart. const csp = JSON.parse(readFileSync('src/consent.gen/csp.json', 'utf8')); const headers = { [csp.headerName]: csp.header };
// The receipt endpoint of the registry. A real site stores the receipt; this one only answers. if (request.method === 'POST' && pathname === '/consent-receipts') { request.resume(); response.writeHead(204, headers).end(); return; }
const file = join('dist', normalize(pathname === '/' ? '/index.html' : pathname)); if (!file.startsWith('dist') || file === join('dist', '_headers') || !existsSync(file)) { response.writeHead(404, headers).end('Not found'); return; } response.writeHead(200, { ...headers, 'Content-Type': types[extname(file)] ?? 'application/octet-stream' }).end(readFileSync(file));}).listen(4173, () => console.log('http://localhost:4173'));node serve.mjsOpen http://localhost:4173 in a browser. You see the banner. Check the header from a second terminal:
curl -sI http://localhost:4173/ | grep -i content-security-policyContent-Security-Policy: default-src 'none'; script-src 'self' 'sha256-…'; style-src 'self'; font-src 'self'; img-src 'self'; connect-src 'self'; frame-src 'self'; media-src 'self'; worker-src 'self'; manifest-src 'self'; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'; upgrade-insecure-requestsThat is the strict default: nothing from any other origin, and no inline script except the guard.
Try it by hand. Click “Reject all”, open the Lisbon page, go back: no “Continue reading” link. Open “Privacy preferences” in the footer, switch on “Continue reading”, save, visit the Lisbon page and return: the link is there. Switch it off again and the key is gone from localStorage.
9. Audit it
Section titled “9. Audit it”Leave the server running. In the second terminal:
npx consent-kit audit http://localhost:4173 --page / --page /lisbon.htmlconsent-kit audit of http://localhost:4173/Pages: /, /lisbon.html
PASS 1. Pre-consent silencePASS 2. Reject means rejectPASS 3. Grant activates exactly what is declaredPASS 4. Withdrawal cleans upPASS 5. GPC honouredPASS 6. Undeclared driftPASS 7. Banner UXPASS Consent receipts: one per decisionPASS Subject requests reachable (the registry declares no subject requests)PASS Coverage: attribute driftPASS Coverage: unexercised declarationsPASS Setup: runtime guard installedPASS Setup: no Content-Security-Policy violations in the page itself
Coverage: 2 of 2 declared artefacts observed; 0 undeclared; 0 used without consent; 0 with attribute drift.
Content-Security-Policy (as generated from the registry): strict.
Audit passed: 13 checks passed (4.2s).The audit drove Chromium through the site several times: without a decision, after rejecting, after accepting, after withdrawing, and with the Global Privacy Control signal. It compared every cookie, storage key and request with the registry. Each check is described in the audit reference.
Break it on purpose
Section titled “Break it on purpose”A passing audit means more once you have seen it fail. Add one line to the end of src/main.ts that writes a key the registry does not know, bypassing the facade:
localStorage.setItem('visits', String(Number(localStorage.getItem('visits') ?? 0) + 1));Rebuild and audit again:
node build.mjsnpx consent-kit audit http://localhost:4173 --page / --page /lisbon.html --check undeclared-driftconsent-kit audit of http://localhost:4173/Pages: /, /lisbon.html
SKIP 1. Pre-consent silenceSKIP 2. Reject means rejectSKIP 3. Grant activates exactly what is declaredSKIP 4. Withdrawal cleans upSKIP 5. GPC honouredFAIL 6. Undeclared drift error localStorage key "visits" is not declared in the registry; it was written before any decision on /. Remove it, or add to privacy.registry.yaml: - id: visits kind: storage area: local key: "visits" purposes: [TODO]SKIP 7. Banner UXSKIP Consent receipts: one per decisionSKIP Subject requests reachableSKIP Coverage: attribute driftSKIP Coverage: unexercised declarationsSKIP Setup: runtime guard installedSKIP Setup: no Content-Security-Policy violations in the page itself
Coverage: 2 of 2 declared artefacts observed; 1 undeclared; 0 used without consent; 0 with attribute drift.
Content-Security-Policy (as generated from the registry): strict.
Audit FAILED: 0 checks passed, 1 failed, 12 skipped (2.7s).--check runs one check and skips the others. The audit exits with code 1 and prints the registry entry to paste, with the one thing it cannot know left as TODO: the purpose. Remove the line and run node build.mjs again.
In a real project the ESLint rule @consent-kit/no-raw-storage reports that line before it reaches a browser; see migrate raw storage calls to the facade.
10. Write the documents and release
Section titled “10. Write the documents and release”Generate the privacy documents:
npx consent-kit docscreated privacy-docs/cookies.en.jsoncreated privacy-docs/cookies.en.mdcreated privacy-docs/field-notices.en.jsoncreated privacy-docs/privacy-policy.en.mdcreated privacy-docs/processors.en.jsoncreated privacy-docs/processors.en.mdcreated privacy-docs/ropa.en.csvcreated privacy-docs/ropa.en.md
unreviewed 70 phrase texts in use have not been legally reviewed (70 en). The documents are stamped as unreviewed drafts. List them with --json.
70 unreviewed phrase texts, 0 overrides, 0 required gaps, 0 advisory gaps. Generated text is not legal advice.Wrote the documents of revision 1 (policy 4e23331f7acb): 8 written, 0 unchanged.Open privacy-docs/privacy-policy.en.md. It starts with a banner that says it is an unreviewed draft. That is accurate: read documents and phrase review before you publish any of it.
Record the registry as released:
npx consent-kit releaseReleased revision 1 on 2026-11-28T12:16:14.120ZPolicy hash: 4e23331f7acbd3fc2e563179052926439d73ebc4d042ac9d540987f3b88ceb64
First release. Every visitor is asked for the first time.
Wrote privacy.lock.json.privacy.lock.json is now the baseline. From here on, consent-kit check compares every edit of the registry with it and tells you whether visitors have to be asked again.
For the build you deploy, generate the guard in its default mode, which blocks what record only notes:
npx consent-kit buildnode build.mjsCommit privacy.registry.yaml, privacy.lock.json, and either the generated files or the step that generates them.
What you built
Section titled “What you built”flowchart LR R[privacy.registry.yaml] -->|consent-kit build| G[src/consent.gen/] G -->|cookieconsent.config.gen.ts, storage.gen.ts| M[src/main.ts] G -->|guard.inline.js| H[pages/*.html] G -->|csp.json| S[serve.mjs] M -->|esbuild| D[dist/] H --> D D --> S S -->|consent-kit audit| A[report] R --> A
One file states what the site does. The banner, the policy, the guard and the storage module are generated from it. The audit holds the running site to it.
If something goes wrong
Section titled “If something goes wrong”| Symptom | Cause |
|---|---|
| The audit fails “Setup: runtime guard installed” and says the browser refused to run the guard because its text does not match the hash | The pages inline one build of the guard and the server sends the policy of another. Run npx consent-kit build with the mode you want, then node build.mjs, and make sure the server sends the current csp.json. |
| The banner has no styling | cookieconsent.css is not served from your own origin. A stylesheet from a CDN is refused by style-src 'self'. |
consent-kit build --check reports stale files right after a build |
The check ran with a different --guard-mode than the build. Use the same flags. |
The audit says "consent-kit audit" needs the optional package @consent-kit/audit |
Install it, and Chromium: npm install --save-dev @consent-kit/audit and npx playwright install chromium. |
| The audit passes although you wrote an undeclared key | The guard was built in enforce mode and blocked the write before the audit could see it. Audit a build made with --guard-mode record. |
- Add a third-party tool: add a vendor with a preset or write a registry entry by hand.
- Change the registry and see what the diff says: release a policy change.
- Store the receipts for real: deploy the receipt endpoint.
- Put the audit in CI: run the audit in CI.
- Understand the layers: how consent flows at runtime.