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.
Runtime API reference
The APIs that run in the browser (the guard, the storage facade, embeds, consent receipts) and the helpers a build script calls to write consent-gated HTML. For how the pieces work together, see How consent flows at runtime.
| Package | Runs in | What it exports |
|---|---|---|
@consent-kit/guard |
browser (and the build, for renderInlineGuard) |
installGuard, renderInlineGuard, isGuardViolation |
@consent-kit/storage |
browser (and the build, for the code generator) | createStorage, cookieConsentAccepted, syncEmbeds, installConsentReceipts, consentReceipt, sendConsentReceipt, renderStorageModule, storageDeclarations |
@consent-kit/compiler |
build | consentScriptTag, consentEmbed, guardManifest, contentSecurityPolicy, compile and more |
@consent-kit/cli |
build | The CLI, plus re-exports for build scripts: parseRegistry, consentScriptTag, consentEmbed, guardManifest, contentSecurityPolicy, describeCspDeviations, renderInlineGuard, buildOutputs |
The guard
Section titled “The guard”The guard is a script that wraps the browser’s storage and injection entry points in the top-level document. Every write is checked against the guard manifest (what the registry declares) and the visitor’s current consent.
It is defence in depth. The Content-Security-Policy is the boundary for scripts and frames; see What the guard does not see.
Two ways to run it
Section titled “Two ways to run it”The inline guard. npx consent-kit build writes guard.inline.js: a self-contained script with the manifest and the mode baked in. Inline it as the first script in <head>.
<head> <meta charset="utf-8" /> <script>/* the exact content of guard.inline.js */</script> ...</head>The guard has to be the first script the parser meets, so that nothing runs before the patches are in place.
installGuard. For code that is bundled, or for tests:
import { installGuard } from '@consent-kit/guard';import manifest from './consent.gen/guard-manifest.json';
const guard = installGuard({ manifest, mode: 'throw' });// laterguard.uninstall();A bundled guard only covers what runs after the bundle. Use the inline guard in production.
installGuard(options)
Section titled “installGuard(options)”Returns a GuardHandle.
| Option | Type | Default | Meaning |
|---|---|---|---|
manifest |
GuardManifest |
required | The content of guard-manifest.json, or guardManifest(registry). |
mode |
'throw' | 'record' | 'report' | 'enforce' |
required | See Modes. |
isAccepted |
(category: string) => boolean |
reads the consent cookie | Category lookup. Anything but a literal true, including a throw, counts as not accepted. |
isServiceAccepted |
(service: string, category: string) => boolean |
reads the consent cookie | Service lookup, with the argument order of CookieConsent’s acceptedService. Asked once per accepted category of an entry that has a service. |
report |
(observation: GuardObservation) => void |
none | Called for reports; see Violation reports. |
reportUrl |
string |
none | Reports are also sent here with navigator.sendBeacon. |
sampleRate |
number, 0 to 1 |
1 |
Share of page loads that report. Applies in report mode only. |
consentCookieName |
string |
"cc_cookie" |
Name of CookieConsent’s consent cookie. |
observeNetwork |
boolean |
false |
Record the origins of fetch, XMLHttpRequest and sendBeacon calls. Never blocks. |
window |
Window |
the global window |
The window to patch. |
isAccepted and isServiceAccepted default independently. If you inject isAccepted because consent does not live in CookieConsent’s cookie, inject isServiceAccepted too, or every entry with a service stays blocked.
GuardHandle:
| Member | Meaning |
|---|---|
observed |
Array of every decision so far (GuardObservation[]). In record mode it is the same array as window.__ck_observed. In the other modes it stops growing at 1000 entries. |
uninstall() |
Restores every patched property and method, disconnects the observer and removes window.__ck_guard. |
renderInlineGuard(options)
Section titled “renderInlineGuard(options)”Returns the source text of the inline guard as a string: an IIFE that installs the guard with the options serialised into it. The output is the same bytes wherever the package is loaded from, which the CSP hash depends on.
Options: manifest, mode, reportUrl, sampleRate, consentCookieName, observeNetwork, with the meanings above. Function options (isAccepted, isServiceAccepted, report) cannot be serialised and are not available: the inline guard always reads the consent cookie.
consent-kit build calls it with the manifest, --guard-mode and --report-url only. To set sampleRate, consentCookieName or observeNetwork, render the guard in your own build script and give the policy its hash:
import { createHash } from 'node:crypto';import { contentSecurityPolicy, guardManifest, renderInlineGuard } from '@consent-kit/cli';
const guard = renderInlineGuard({ manifest: guardManifest(registry), mode: 'report', reportUrl: '/guard-reports', sampleRate: 0.1,});// Hash exactly the text that goes between <script> and </script>.const hash = createHash('sha256').update(guard, 'utf8').digest('base64');const csp = contentSecurityPolicy(registry, { inlineScriptHashes: [hash] });isGuardViolation(error)
Section titled “isGuardViolation(error)”True for the error the guard throws in throw mode (error.name === 'ConsentGuardError'). The error carries kind, key, reason, artefact, missing, missingServices when a service is off, and registryEntry when the reason is undeclared: a ready-to-paste artefact entry for privacy.registry.yaml with TODO where only a person knows the answer.
--guard-mode of consent-kit build defaults to enforce.
| Situation | throw |
record |
report |
enforce |
|---|---|---|---|---|
| Undeclared write | throws ConsentGuardError |
allowed, recorded | blocked, reported (sampled) | blocked, reported (always) |
| Declared, consent missing | throws ConsentGuardError |
blocked | blocked, not reported | blocked, not reported |
| Declared, consent given or none required | allowed | allowed | allowed | allowed |
| Deletion | allowed | allowed | allowed | allowed |
| Same-origin script or iframe that no entry matches | allowed | allowed | allowed | allowed |
| The guard itself fails | throws | blocked, reported | blocked, reported | blocked, reported |
throwis for development and tests. The error is thrown at the offending call, so the stack points at it. An invalid manifest fails at install and leaves nothing patched.recordlets undeclared writes through and keeps the full list of decisions onwindow.__ck_observed. It is the mode the audit reads. It still blocks a declared artefact that lacks consent.reportblocks, and reports undeclared writes on a sample of page loads.enforceblocks, and reports every undeclared write.sampleRateis ignored.
report and enforce differ only in sampling. No mode reports a declared write that lacks consent: that is the gate working, not a violation.
What “blocked” means depends on the API:
| API | A blocked call |
|---|---|
document.cookie = ... |
The assignment is ignored. |
cookieStore.set() |
Returns a resolved promise; nothing is written. |
localStorage.setItem(), sessionStorage.setItem() |
Returns undefined; nothing is written. |
indexedDB.open() |
Returns a request-shaped object whose onerror handler and error listeners are called asynchronously with a SecurityError. |
Inserted <script src> |
The element gets type="text/plain" and is removed from the document. |
Inserted <iframe src> |
The element is removed from the document. |
In throw mode a blocked script or iframe is also removed, and the error surfaces as an uncaught error on the window, because a MutationObserver callback has no caller to throw to.
What the guard intercepts
Section titled “What the guard intercepts”| Surface | Hook | Key that is matched |
|---|---|---|
| Cookies | The document.cookie setter |
The cookie name: the text before the first =. |
| Cookies | cookieStore.set, cookieStore.delete, where the browser has them |
The cookie name. |
| Web storage | Storage.prototype.setItem and removeItem, for the window’s localStorage and sessionStorage |
The storage key. |
| IndexedDB | indexedDB.open |
The database name. |
| Scripts and iframes | A MutationObserver on the document, for inserted <script src> and <iframe src> and for a src attribute that changes |
Origin and path of the URL, without query and hash. |
Network, only with observeNetwork |
fetch, XMLHttpRequest.prototype.open, navigator.sendBeacon |
The origin of the request. Recorded, never blocked, never reported. |
Deletions are always allowed, so cleanup after a withdrawal works even for an undeclared key: a cookie write with Max-Age of zero or less, or without Max-Age and with Expires in the past; cookieStore.delete; a cookieStore.set whose expires has passed; removeItem.
The observer skips a <script> with type="text/plain" (it is inert until CookieConsent re-inserts it, which is checked then), inline scripts, and about: URLs.
A same-origin <script src> or <iframe src> that no manifest entry matches is first-party code. It is allowed in every mode, recorded with the reason first-party and never reported. A same-origin entry that does match applies its consent requirement like any other.
What the guard does not see
Section titled “What the guard does not see”These limits are deliberate and are stated in the source of the guard.
- Reads. Nothing is blocked or recorded when a script reads a cookie or a storage key.
- Other frames. Only the top-level document’s prototypes are patched. A script can take an unpatched API from a fresh iframe, and a cross-origin iframe has its own storage.
- Property access on storage.
localStorage.foo = 'x'andlocalStorage['foo'] = 'x'do not go throughsetItem. Storage#clearandindexedDB.deleteDatabase. They are deletions and are not patched.- Server-set cookies. A
Set-Cookieheader and HttpOnly cookies never touchdocument.cookie. - Timing of scripts and iframes. The observer runs after insertion. Marking a script
text/plainand removing it reliably stops a script the parser inserted. For an element inserted by script, the request may already have started, and a fetched script may still execute. - Stylesheets, fonts and media. There is no hook for a
<link>, a CSSurl()or a<video>. These kinds are in the manifest’sendpointslist only so that the audit can tell a declared load from an undeclared one. - Network requests. They are observed only with
observeNetwork, and never blocked.
The CSP stops an undeclared origin whatever the guard saw. See Threat model and limits.
How consent is read
Section titled “How consent is read”By default the guard parses CookieConsent’s cookie (cc_cookie) on every check, so a consent change applies at once. It reads the cookie through the original document.cookie getter, captured at install.
The cookie value is URL-encoded JSON. The guard uses two fields:
categories: an array of accepted category ids. A category id is a consent purpose id.services: an object from category id to an array of accepted service ids. A service id is a processor id.
A manifest entry is consented when every id in its categories is accepted and, if it has a service, that service is accepted in every one of those categories. An entry with an empty categories list is always allowed.
The lookup fails closed: no cookie, a cookie that does not parse, or a field of the wrong shape means nothing is accepted.
The guard manifest
Section titled “The guard manifest”guard-manifest.json has seven lists: cookies, localStorage, sessionStorage, indexedDB, scripts, iframes and endpoints. Each entry is:
{ "id": "acme_video_embed", "name": "http://127.0.0.1:4174/embed", "categories": ["media"], "service": "acme-video"}| Field | Meaning |
|---|---|
id |
The artefact id, for messages and reports. |
name or pattern |
Exactly one. name is an exact name or a URL prefix; pattern is a RegExp source. |
categories |
Consent purpose ids that must all be accepted. Empty means always allowed. |
service |
The artefact’s processor id, present when the entry requires consent and the artefact has a processor. |
Matching:
cookies,localStorage,sessionStorage,indexedDB:namematches the key exactly. Otherwise eachpatternis tested against the whole key.scripts,iframes,endpoints:nameis an origin (https://plausible.io), an absolute URL prefix (https://cdn.example/widgets/) or a site-relative path that starts with a single/. A URL matches when its origin is equal and its path is under the prefix by whole segments:/collectmatches/collectand/collect/xbut not/collector. A bare origin matches every path on it. The longest matching prefix wins. Apatternis tested against origin and path, without query and hash.
How the compiler fills the lists:
- A script’s
srcnames one file, so its entry is that file’s full path. - An iframe’s
srcand an endpoint’s or pixel’surlare prefixes as declared. - Pixels, endpoints, stylesheets, fonts and media files all go into
endpoints. - CookieConsent’s own
cc_cookieis added as always allowed, unless the registry declares a cookie with that name.
A manifest entry the guard cannot use (an invalid pattern, an unparseable URL) is dropped and reported, so what it would have matched is undeclared.
The manifest keeps declared paths. The CSP is origin-level, so a path nothing declares on a declared origin passes the CSP and is caught by the guard and the audit.
Violation reports
Section titled “Violation reports”A report is one GuardObservation. The guard reports:
- an undeclared write, in
reportmode (on sampled page loads) and inenforcemode; - an internal error of the guard, in every mode and regardless of sampling.
Each combination of kind, key and reason is reported at most once per page load. Whether a page load is in the sample is decided once, when the guard installs.
A report goes to the report callback, when there is one, and to reportUrl, when there is one. The request to reportUrl is made with the navigator.sendBeacon captured before the guard patched anything, with this JSON text as the body:
{ "v": 1, "path": "/video.html", "observation": { "kind": "localStorage", "key": "debug_flag", "artefact": null, "reason": "undeclared", "outcome": "blocked", "missing": [], "mode": "enforce", "ts": 1764331200000 }}path is location.pathname only: no query string, no origin. A reporter that throws never reaches the page.
Set the URL at build time:
npx consent-kit build --guard-mode report --report-url /guard-reportsconsent-kit does not ship a receiver for these reports, and the build does not add the report URL to the Content-Security-Policy. A path on the site’s own origin is covered by connect-src 'self'. For another origin, declare it as an endpoint artefact.
GuardObservation:
| Field | Meaning |
|---|---|
kind |
cookie, localStorage, sessionStorage, indexedDB, script, iframe or network. |
key |
Cookie name, storage key, database name, the script or iframe URL without query and hash, or the request origin. |
artefact |
Id of the matched manifest entry, or null. |
reason |
ok, undeclared, first-party, unconsented, deletion, observed (network) or internal-error. |
outcome |
allowed, blocked or thrown. |
missing |
Required categories that are not accepted. |
missingServices |
{ category, service } for each accepted category in which the required service is off. Present only when non-empty. |
declared |
network only: whether the request matched an entry of endpoints. |
mode |
The guard’s mode. |
ts |
Epoch milliseconds. |
error |
The message, for internal-error. |
window.__ck_observed and window.__ck_guard
Section titled “window.__ck_observed and window.__ck_guard”In record mode the guard appends every decision, allowed ones included, to window.__ck_observed. If the array already exists, the guard appends to it. The audit reads it to learn what the guard blocked.
In the other modes the list is not put on the window. It is available as handle.observed from installGuard and is capped at 1000 entries: a debugging aid, not a log.
window.__ck_guard is { mode } once the guard has installed. Its absence means no guard is running. The audit uses it to tell a guard that ran from an inline script the browser refused.
The storage facade
Section titled “The storage facade”@consent-kit/storage replaces document.cookie, localStorage, sessionStorage and indexedDB.open in first-party code. Keys are limited to what the registry declares, and consent is checked on every call.
Nothing in the facade throws. A write that is not allowed, or that the browser rejects, returns { ok: false, reason }.
createProjectStorage (generated)
Section titled “createProjectStorage (generated)”npx consent-kit build writes storage.gen.ts. It exports the registry’s cookie and storage artefacts as declarations, and createProjectStorage, which binds them:
function createProjectStorage<Values = {}>( isAccepted: IsAccepted, options?: { window?: StorageWindow },): ProjectStorage<Values>;The example site creates its facade once:
import { cookieConsentAccepted } from '@consent-kit/storage';import { createProjectStorage } from '#consent/storage.gen.ts';
type Theme = 'light' | 'dark';
const isAccepted = cookieConsentAccepted();const storage = createProjectStorage<{ theme: Theme }>(isAccepted);Because the declarations are literal types, a key that is not declared is a compile error: storage.local.get('thmee') does not typecheck.
The generated module imports @consent-kit/storage, so the package has to be a dependency of your site.
createStorage(options)
Section titled “createStorage(options)”The function createProjectStorage calls. Use it directly only with hand-written declarations.
| Option | Type | Meaning |
|---|---|---|
declarations |
StorageDeclarations |
What may be stored: cookies, local, session and indexedDB, each with keys (exact names) and patterns (by artefact id). |
isAccepted |
(category: string, service?: string) => boolean |
Is the category accepted and, when service is given, is that service accepted in it. Called on every write; never cached. An isAccepted that throws counts as not accepted. |
window |
StorageWindow |
Defaults to the global window. Without one (server-side rendering) reads return undefined and writes are refused as unavailable. |
cookieConsentAccepted(cookieName?, doc?)
Section titled “cookieConsentAccepted(cookieName?, doc?)”Returns an isAccepted function that reads CookieConsent’s consent cookie on every call, without importing the library. cookieName defaults to "cc_cookie"; doc defaults to the global document.
It fails closed: no document, no cookie, or a value that does not parse or has the wrong shape means not accepted. With a service argument, the service must be listed under that category in the cookie’s services field.
Areas: storage.cookies, storage.local, storage.session
Section titled “Areas: storage.cookies, storage.local, storage.session”Each area has the same methods.
| Method | Returns | Consent-gated |
|---|---|---|
get(key) |
The stored value, or undefined |
no |
get(key, validate) |
The value if validate(value) is true, else undefined |
no |
set(key, value) |
WriteResult |
yes |
setThirdParty(key, value) |
WriteResult |
yes |
remove(key) |
RemoveResult |
no |
matching(artefactId) |
An object with get, set or setThirdParty, and remove, for keys declared by a pattern |
as above |
get. Reading is not consent-gated. The stored text is JSON-parsed; text that is not JSON, written by other code, comes back as the raw string. An undeclared key reads as undefined.
set. Writes the JSON-serialised value if every category the key requires is accepted right now, and the key’s service in each of them. A key that requires no consent is always written. For a cookie, the serialised value is URL-encoded.
setThirdParty. The same as set, for a key that belongs to a third-party processor. set refuses such a key with third_party. The separate name keeps these writes deliberate and easy to find.
remove. Never consent-gated, so cleanup always works.
matching(artefactId). For an artefact declared with pattern instead of an exact name. Each call checks the concrete key against the pattern. With a storage artefact draft_keys declared as pattern: '^draft:':
const drafts = storage.local.matching('draft_keys');drafts.set('draft:42', { text: 'hello' }); // { ok: true }drafts.set('other', 1); // { ok: false, reason: 'key_mismatch', pattern: '^draft:' }A write is refused with the first of these that applies:
reason |
When | Extra fields |
|---|---|---|
undeclared |
The key, or the pattern’s artefact id, is not in the declarations. With generated declarations this is only reachable from untyped code. | |
key_mismatch |
matching() only: the key does not match the declared pattern. |
pattern |
http_only |
The cookie is declared httpOnly: script cannot touch it. |
|
third_party |
A third-party key was written with set. |
|
invalid_key |
Cookies only: not a legal cookie name. | |
not_consented |
A required category is not accepted, or the service is off in it. | missing (the category ids), service when the key has one |
unserialisable |
JSON.stringify threw or produced nothing: a cycle, a BigInt, undefined, a function. |
|
unavailable |
No window, or the browser refused: storage disabled, quota exceeded. |
remove can return undeclared, key_mismatch, http_only, invalid_key or unavailable.
An HttpOnly cookie is excluded from the key types of every method. From untyped code, get returns undefined for it.
Value types and type guards
Section titled “Value types and type guards”The registry says what a key is for, not what is stored in it. By default set accepts any value and get returns unknown.
State the value types once, where the facade is created:
const storage = createProjectStorage<{ theme: 'light' | 'dark' }>(isAccepted);
storage.local.set('theme', 'dark'); // typechecksstorage.local.set('theme', 'blue'); // compile errorstorage.local.get('theme'); // 'light' | 'dark' | undefinedThe map is keyed by declared name, or by artefact id for a pattern. It may cover any subset of the names. A name that is not declared is a compile error.
The type is a claim, not a check: get trusts it. To check a stored value at runtime, pass a type guard. A value that fails the guard reads as undefined:
const isTheme = (value: unknown): value is Theme => value === 'light' || value === 'dark';
applyTheme(storage.local.get('theme', isTheme) ?? 'light');Cookie attributes
Section titled “Cookie attributes”set on a cookie takes a name and a value, nothing else. The attributes come from the artefact in the registry:
| Attribute | Source |
|---|---|
Path |
Always /. |
Max-Age |
duration: "<n>d" becomes n × 86400 seconds; session leaves it out. |
Domain |
domain, when declared. |
SameSite |
sameSite, when declared. |
Secure |
secure: true. |
remove expires the cookie with its declared Domain. If the cookie is still there, it expires it again without a Domain, for a cookie that was set host-only.
storage.openDatabase(name, version?)
Section titled “storage.openDatabase(name, version?)”Consent-gated indexedDB.open. The name is matched against the declared database names, then against the declared patterns.
Returns { ok: true, request } with the IDBOpenDBRequest, or a refusal with the reason undeclared, not_consented or unavailable.
storage.clearUnconsented()
Section titled “storage.clearUnconsented()”Cleanup after a withdrawal. Removes every declared cookie, localStorage and sessionStorage entry whose consent requirement is not met right now, and returns what it removed as { area, key, id } entries.
- For an exact declaration it removes the key. For a pattern declaration it removes every existing key that matches.
- Entries that need no consent, and anything the registry does not declare, are never touched.
- Third-party keys are included: this is how a vendor’s
localStoragekey is removed. - A cookie is listed only if it is really gone afterwards. HttpOnly cookies are skipped.
- For IndexedDB,
deleteDatabaseis requested for each unconsented database declared by exact name. These are listed withpending: true: the deletion completes later, and whether the database existed is not known. Databases declared by pattern are not covered.
It is synchronous and never throws. Call it from CookieConsent’s onChange, because CookieConsent’s own autoClear only knows cookies:
void CookieConsent.run({ ...cookieConsentConfig, onChange: () => { storage.clearUnconsented(); },});What the declarations contain
Section titled “What the declarations contain”For each cookie and storage artefact, storage.gen.ts records:
| Field | Meaning |
|---|---|
id |
The artefact id. |
categories |
The artefact’s purposes whose basis is consent. All are required. |
service |
The artefact’s processor id, when it has a processor and at least one category. |
thirdParty |
true when the artefact has a processor that is not marked firstParty. |
attributes, httpOnly |
Cookies only. |
renderStorageModule(registry) returns the source of storage.gen.ts, and storageDeclarations(registry) the declarations object. consent-kit build calls the first for you.
Embeds
Section titled “Embeds”syncEmbeds(isAccepted, root?)
Section titled “syncEmbeds(isAccepted, root?)”Brings every embed placeholder under root (default: document) in line with the current consent. A placeholder is the <div data-ck-embed ...> that consentEmbed writes.
- When the placeholder’s category is accepted, and its service when it names one: the placeholder’s child elements are hidden, an
<iframe>with thesrcandtitlefrom the placeholder is appended, and the placeholder getsdata-ck-embed="loaded". - When it is not accepted: the iframe is removed, the hidden children are shown again and the attribute goes back to
data-ck-embed="".
Returns { loaded, unloaded }: how many embeds changed in this call.
It is idempotent, so call it from both onConsent and onChange. It fails closed: a placeholder without data-category or data-src, or an isAccepted that throws or returns anything but true, loads nothing.
The iframe it creates has src, title (when the placeholder has data-title) and the marker attribute data-ck-embed-frame. It sets no size and no other attribute; style it with CSS.
See Embed an iframe behind consent.
Consent receipts
Section titled “Consent receipts”When the registry declares receipts.endpoint, the generated cookieconsent.config.gen.ts imports installConsentReceipts and calls it at module load. A site that imports the generated config needs no other code. What a receipt is and what the endpoint does with it is in Receipts and server reference.
installConsentReceipts(settings, environment?)
Section titled “installConsentReceipts(settings, environment?)”Sends one receipt for every decision CookieConsent reports. Returns { uninstall() }.
settings, written by the build:
| Field | Meaning |
|---|---|
endpoint |
Site-relative path or https URL that receives the POST. |
policyHash |
The policy hash of the build. |
revision |
CookieConsent’s revision of the build. |
purposes |
Every consent purpose id with its version. |
environment, all optional and meant for tests: window (where the events are listened for), now, navigator and fetch.
It listens on the window for CookieConsent’s own events:
| Event | Receipt event |
|---|---|
cc:onFirstConsent |
first |
cc:onChange |
change |
These fire whatever callbacks the site passes to CookieConsent.run, so a site that sets its own onChange still sends its receipts.
The receipt is built from the event’s detail.cookie. If that carries no consentId, nothing is sent. Under Global Privacy Control, CookieConsent treats the visitor as having refused and fires neither event, so no receipt is sent.
It installs once per window; a second call while the first is installed does nothing. It never throws into the page.
sendConsentReceipt(endpoint, receipt, transport?)
Section titled “sendConsentReceipt(endpoint, receipt, transport?)”POSTs one receipt and returns whether a request was handed to the browser.
navigator.sendBeacon(endpoint, body), which survives the page unloading.- If there is no
sendBeacon, or it returnsfalseor throws:fetchwithmethod: 'POST',keepalive: trueand the headerContent-Type: text/plain;charset=UTF-8.
The body is the receipt as JSON text. text/plain needs no CORS preflight. There are no retries.
consentReceipt(event, cookie, settings, now?)
Section titled “consentReceipt(event, cookie, settings, now?)”Builds the receipt object for one decision, or returns null when cookie has no consentId. The receipt holds consentId, event, accepted and rejected (each a list of { purpose, version }, sorted by id), policyHash, revision and timestamp. Nothing else is sent: no user agent, no page URL.
Build-script helpers
Section titled “Build-script helpers”These run in Node, in the script that writes your HTML. @consent-kit/cli re-exports them, so a build script needs one dependency:
import { readFileSync } from 'node:fs';import { consentEmbed, consentScriptTag, parseRegistry } from '@consent-kit/cli';
const parsed = parseRegistry(readFileSync('privacy.registry.yaml', 'utf8'));if (!parsed.ok) throw new Error(parsed.errors.map((e) => e.message).join('; '));const registry = parsed.registry;parseRegistry from @consent-kit/cli resolves presets against the built-in catalogue, as the CLI does.
consentScriptTag(registry, artefactId)
Section titled “consentScriptTag(registry, artefactId)”Returns the HTML for a declared script artefact.
| The script is bound to | Returns |
|---|---|
| One consent purpose | An inert tag that CookieConsent activates on consent. |
| No consent purpose | <script src="..."></script> |
| Several consent purposes | Throws. CookieConsent’s data-category holds one category. |
For the example registry:
consentScriptTag(registry, 'acme_script');<script type="text/plain" data-category="analytics" data-service="acme-analytics" data-src="http://127.0.0.1:4174/analytics.js"></script>data-category is the consent purpose id. data-service is the processor id and is left out when the artefact has no processor. CookieConsent activates the tag only while that service is enabled in that category.
It throws when the id is unknown or is not a script artefact. The same tag is printed by npx consent-kit script-tag <artefact-id>; see the CLI reference.
consentEmbed(registry, artefactId, options?)
Section titled “consentEmbed(registry, artefactId, options?)”Returns the HTML for a declared iframe artefact.
| Option | Meaning |
|---|---|
title |
Accessible name of the iframe. Carried as data-title until the embed is activated. |
src |
The concrete URL to embed, when the declared src is an origin or a prefix. It must be on the same origin and under the declared path by whole segments. Default: the declared src. |
placeholder |
HTML shown inside the placeholder until the embed is activated. Inserted as given, not escaped. |
| The iframe is bound to | Returns |
|---|---|
| One consent purpose | An inert placeholder for syncEmbeds. |
| No consent purpose | <iframe src="..." title="..."></iframe> |
| Several consent purposes | Throws. |
For the example registry:
consentEmbed(registry, 'acme_video_embed', { title: 'Acme Video player', placeholder: '<p>Video by Acme Video.</p>',});<div data-ck-embed data-category="media" data-service="acme-video" data-src="http://127.0.0.1:4174/embed" data-title="Acme Video player"><p>Video by Acme Video.</p></div>Without options the placeholder is empty:
<div data-ck-embed data-category="media" data-service="acme-video" data-src="http://127.0.0.1:4174/embed"></div>It throws when the id is unknown, when the artefact is not an iframe, and when options.src is not under the declared src:
consent-kit: "http://127.0.0.1:4174/embedded" is not under the declared src of iframe "acme_video_embed" (http://127.0.0.1:4174/embed)CookieConsent has no convention for embeds, so nothing loads until your code calls syncEmbeds.
guardManifest(registry)
Section titled “guardManifest(registry)”Returns the guard manifest as an object: the content of guard-manifest.json. Entries are sorted by artefact id.
contentSecurityPolicy(registry, options?)
Section titled “contentSecurityPolicy(registry, options?)”Returns the generated policy: header, headerName, meta, directives, level and deviations. The policy itself is described in the Content-Security-Policy reference.
| Option | Meaning |
|---|---|
inlineScriptHashes |
Base64 SHA-256 digests of inline scripts to allow in script-src. Each must be the digest of the script element’s exact text. consent-kit build passes the hash of guard.inline.js. |
inlineStyleHashes |
Base64 SHA-256 digests of inline <style> elements to allow in style-src. Hashes do not cover style="..." attributes. |
noncePlaceholder |
Adds 'nonce-<placeholder>' to script-src, for a server to replace on each response, for example {{CSP_NONCE}}. Letters, digits and {}_-. only. |
A hash that is not 44 characters of base64, or a placeholder with other characters, throws.
consent-kit build uses inlineScriptHashes only. For inline styles or a nonce, call the function from your own build script.
compile(registry, options)
Section titled “compile(registry, options)”Exported by @consent-kit/compiler only. Returns five build outputs as a map from file name to content, without writing anything: registry.gen.ts, policy.json, cookieconsent.config.gen.ts, guard-manifest.json and csp.json.
options takes revision (required: CookieConsent’s revision number) and the three contentSecurityPolicy options.
compile does not render the inline guard, so its csp.json has no guard hash unless you pass one.
buildOutputs(registry, options)
Section titled “buildOutputs(registry, options)”Exported by @consent-kit/cli. Returns every file consent-kit build writes, as a map from file name to content: the compile outputs with the guard’s hash in the policy, plus guard.inline.js, storage.gen.ts, _headers and, when the registry declares a receipt endpoint, receipts.manifest.gen.json.
options: revision, guardMode, and optionally reportUrl and history. The files are listed in Generated files.