# Getting started

> A tutorial that takes a small static site from an empty folder to a passing browser audit and a first release.

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](/docs/manual/guides/add-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.yaml` that 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

You need Node.js 22 or newer and a terminal.

> [!NOTE]
> The commands below install the published packages from npm. To work on consent-kit itself, follow the [repository README](https://github.com/pavelpascari/consent-kit#readme).

## 1. Create the project

```sh
mkdir trip-notes && cd trip-notes
npm init -y
npm pkg set type=module
npm install vanilla-cookieconsent @consent-kit/storage
npm install --save-dev @consent-kit/cli @consent-kit/audit esbuild
npx 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

Create `privacy.registry.yaml`. It is the only privacy file you write by hand.

```yaml
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-receipts
```

What you just declared:

- **Two purposes.** `essential` rests on a legitimate interest and has no toggle. `reading_position` rests on consent: it is off until the visitor agrees.
- **Two artefacts.** `cc_cookie` is the cookie the banner stores the choice in. `last_page` is 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-receipts` itself.

The controller, its address and the authority are example values. The fields are explained in [the registry model](/docs/manual/concepts/registry-model/).

## 3. Check it

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

```
No privacy.lock.json: nothing has been released yet.
The first release will be revision 1; every visitor is asked for the first time.

check passed
```

To 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

```sh
npx consent-kit build --guard-mode record
```

```
created  src/consent.gen/_headers
created  src/consent.gen/cookieconsent.config.gen.ts
created  src/consent.gen/csp.json
created  src/consent.gen/guard-manifest.json
created  src/consent.gen/guard.inline.js
created  src/consent.gen/policy.json
created  src/consent.gen/receipts.manifest.gen.json
created  src/consent.gen/registry.gen.ts
created  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](/docs/manual/reference/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

Create `src/main.ts`:

```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 `localStorage` directly. `storage.local.set('last_page', …)` writes only when the visitor has accepted `reading_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

Create `pages/index.html`:

```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:

```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>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

Create `build.mjs`:

```js
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');
```

```sh
node build.mjs
```

> [!WARNING]
> Step 3 must not change the guard's text. No trimming, no re-indenting, no minifier over the HTML afterwards. The browser runs the script only if its text matches the hash in the policy, and it refuses silently when it does not.

## 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`:

```js
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'));
```

```sh
node serve.mjs
```

Open `http://localhost:4173` in a browser. You see the banner. Check the header from a second terminal:

```sh
curl -sI http://localhost:4173/ | grep -i content-security-policy
```

```
Content-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-requests
```

That 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

Leave the server running. In the second terminal:

```sh
npx consent-kit audit http://localhost:4173 --page / --page /lisbon.html
```

```
consent-kit audit of http://localhost:4173/
Pages: /, /lisbon.html

PASS  1. Pre-consent silence
PASS  2. Reject means reject
PASS  3. Grant activates exactly what is declared
PASS  4. Withdrawal cleans up
PASS  5. GPC honoured
PASS  6. Undeclared drift
PASS  7. Banner UX
PASS  Consent receipts: one per decision
PASS  Subject requests reachable (the registry declares no subject requests)
PASS  Coverage: attribute drift
PASS  Coverage: unexercised declarations
PASS  Setup: runtime guard installed
PASS  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](/docs/manual/reference/audit/).

### 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:

```ts
localStorage.setItem('visits', String(Number(localStorage.getItem('visits') ?? 0) + 1));
```

Rebuild and audit again:

```sh
node build.mjs
npx consent-kit audit http://localhost:4173 --page / --page /lisbon.html --check undeclared-drift
```

```
consent-kit audit of http://localhost:4173/
Pages: /, /lisbon.html

SKIP  1. Pre-consent silence
SKIP  2. Reject means reject
SKIP  3. Grant activates exactly what is declared
SKIP  4. Withdrawal cleans up
SKIP  5. GPC honoured
FAIL  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 UX
SKIP  Consent receipts: one per decision
SKIP  Subject requests reachable
SKIP  Coverage: attribute drift
SKIP  Coverage: unexercised declarations
SKIP  Setup: runtime guard installed
SKIP  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](/docs/manual/guides/migrate-to-the-storage-facade/).

## 10. Write the documents and release

Generate the privacy documents:

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

```
created  privacy-docs/cookies.en.json
created  privacy-docs/cookies.en.md
created  privacy-docs/field-notices.en.json
created  privacy-docs/privacy-policy.en.md
created  privacy-docs/processors.en.json
created  privacy-docs/processors.en.md
created  privacy-docs/ropa.en.csv
created  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](/docs/manual/concepts/documents-and-phrase-review/) before you publish any of it.

Record the registry as released:

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

```
Released revision 1 on 2026-11-28T12:16:14.120Z
Policy 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:

```sh
npx consent-kit build
node build.mjs
```

Commit `privacy.registry.yaml`, `privacy.lock.json`, and either the generated files or the step that generates them.

## What you built

```mermaid
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

| 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`. |

## Next

- Add a third-party tool: [add a vendor with a preset](/docs/manual/guides/add-a-vendor-with-a-preset/) or [write a registry entry by hand](/docs/manual/guides/write-a-registry-entry/).
- Change the registry and see what the diff says: [release a policy change](/docs/manual/guides/release-a-policy-change/).
- Store the receipts for real: [deploy the receipt endpoint](/docs/manual/guides/deploy-the-receipt-endpoint/).
- Put the audit in CI: [run the audit in CI](/docs/manual/guides/run-the-audit-in-ci/).
- Understand the layers: [how consent flows at runtime](/docs/manual/concepts/runtime-consent-flow/).
