test/consentLogUpgrade.test.ts: a site without the log (migrations applied) upgraded to 1.17.0 — without a migration the site works and a consent write answers 503 with one log line; migrate:create adds only consent_records (and the lock-relation column) and writes succeed. SQLite always; Postgres with IAPL_TEST_PG_URL. Docs say exactly what the migration creates. Co-Authored-By: Claude Opus 5.5 <[email protected]>
641 lines
41 KiB
Markdown
641 lines
41 KiB
Markdown
# consent
|
||
|
||
Cookie consent banner (GDPR): 4 categories (necessary / functional /
|
||
analytics / marketing), stored in a versioned cookie, Google Consent Mode,
|
||
content from the CookieSettings global. A settings window in three modes to pick
|
||
from (`settings`: in the bar, small window, large window with cookie details).
|
||
Default look in plain Tailwind, overridable.
|
||
|
||
## Dependency
|
||
|
||
The banner uses an icon from `lucide-react` — a regular `dependencies` entry of
|
||
the package (`^0.400.0`), installed together with IAPL; you add nothing in the
|
||
project.
|
||
|
||
## Config
|
||
|
||
The **CookieSettings** global — **Cookies** in the admin (slug `cookie-settings`, group *Privacy*) — is always
|
||
built. Tabs: *Banner*, *Settings window*, *Categories*, *Cookie list*; with the cookie scanner also
|
||
*Review and approve* and *Site check* (one entry for everything about cookies — see
|
||
[cookie-scanner.md → Admin layout](./cookie-scanner.md#admin-layout)). Public read (`read: () => true` — the banner reads it for anonymous
|
||
visitors); `update` is limited to the `admin` and `editor` roles (`adminOrEditor` —
|
||
consent texts are legal copy, not for plain `user` accounts). To change it:
|
||
`iapl({ globalOverrides: { 'cookie-settings': { access: { update } } } })`.
|
||
The only plugin option in this module is `consentLog` (below). The editor manages
|
||
the banner content (message, buttons, categories, settingsTitle) in the panel,
|
||
localized. The privacy policy link comes from system pages (`privacyPolicy`), not
|
||
from a separate field.
|
||
|
||
**Privacy policy link in the banner (since 1.7.12)** — zero code:
|
||
|
||
| What | Where from |
|
||
|---|---|
|
||
| Where it leads | Site settings → System pages → Privacy Policy |
|
||
| Link text | Cookies → `privacyLinkLabel` (per language) |
|
||
| When the text is empty | title of the policy page in that language |
|
||
|
||
`privacyPolicy` options in `getConsentTexts`: omit (automatic), `false` (no
|
||
link), `{ page }` (your own page, read with `locale: 'all'`). The `label`
|
||
parameter is **deprecated** — text hard-coded in code breaks A0 with several
|
||
languages; it works only when the panel field is empty. Remove it from projects
|
||
when you update them.
|
||
|
||
## Front — Provider + banner
|
||
|
||
Usually one line in the layout (PROGRAMISTA §2.8) — `SiteProviders` (`/rsc`) wires the provider,
|
||
banner, button and `Analytics` in the right order, with texts from `getSiteShell(locale).consent`:
|
||
```tsx
|
||
<SiteProviders shell={await getSiteShell(locale)}
|
||
banner={<CookieBanner settings="detailed" classNames={…} />}>{children}</SiteProviders>
|
||
```
|
||
`SiteProviders` also takes `cookieMap`, `banner={false}`, `cookieButton={false}`
|
||
(or your own element), `gpc` (Global Privacy Control, below), `maxAgeDays` (re-ask period),
|
||
`logEndpoint` (default: the shell's consent log endpoint; `false` = not posted) and
|
||
`analytics={false | { consentMode, defer, deferTimeoutMs }}`
|
||
(`consentMode: 'basic'` = no Google request before consent — see [analytics.md](./analytics.md)).
|
||
|
||
By hand (your own layout) — the same from the individual parts:
|
||
|
||
The provider wraps the app; the banner and the button render themselves. Import from
|
||
`@intecion/ipal-kit/client`:
|
||
|
||
```tsx
|
||
// app/(frontend)/[locale]/layout.tsx
|
||
import { ConsentProvider, CookieBanner, CookieButton } from '@intecion/ipal-kit/client'
|
||
import { getConsentTexts } from '@intecion/ipal-kit'
|
||
|
||
export default async function Layout({ children, params }) {
|
||
const { locale } = await params
|
||
const payload = await getPayload({ config })
|
||
|
||
// texts from Cookie banner; the policy link is automatic:
|
||
// target = System pages → Privacy Policy, text = Cookies → privacyLinkLabel
|
||
const texts = await getConsentTexts({ payload, config: i18nConfig, locale })
|
||
|
||
return (
|
||
<ConsentProvider texts={texts}>
|
||
{children}
|
||
<CookieBanner />
|
||
<CookieButton />
|
||
</ConsentProvider>
|
||
)
|
||
}
|
||
```
|
||
|
||
`ConsentProvider` — props: `texts` (required, `ConsentTexts` from `getConsentTexts`),
|
||
`cookieMap` (extra cookies to delete on withdrawal), `logEndpoint`
|
||
(consent log — pass `"/api/ipal/consent"` when you wire the provider by hand; `SiteProviders` does it itself),
|
||
`gpc` (`'honour'` default, `'ask'`, `false` — [Global Privacy Control](#global-privacy-control-1170)),
|
||
`maxAgeDays` (days a choice is kept, default 180), `nonce` (CSP nonce for the banner's first-paint script),
|
||
`cookieValue` (optional server-read cookie — [First paint](#first-paint-the-banner-is-part-of-the-first-render-1170)).
|
||
`CookieBanner` does not render after a decision, `CookieButton` —
|
||
the opposite (it shows only after a decision and reopens the banner). Since 1.17.0 the banner is in
|
||
the server HTML and painted with the page, not after hydration (next section).
|
||
|
||
Built-in banner texts follow the page language: `consentFallback(locale)` → `CONSENT_FALLBACK_PL` on `pl`,
|
||
`CONSENT_FALLBACK` (English) otherwise; panel values always win. Category names for your own selects:
|
||
`CONSENT_CATEGORY_LABELS` (`{ en, pl }` per category), `consentCategoryOptions()`. `<CookieTable>`
|
||
takes `locale` and optional `labels`; defaults: `COOKIE_TABLE_LABELS` (`@intecion/ipal-kit/rsc`).
|
||
|
||
`getConsentTexts({ payload, config, locale, privacyPolicy?, settingsSlug? })` —
|
||
`settingsSlug` is the SiteSettings slug for the automatic link (default
|
||
`'site-settings'`). Empty fields in the panel → English fallback.
|
||
|
||
| `CookieBanner` prop | Default | Description |
|
||
|---|---|---|
|
||
| `classNames` | — | slots (table below) — a given one replaces the default |
|
||
| `equalChoice` | `true` (since 1.17.0) | "Reject" styled like "Accept all"; `false` = the secondary look (before 1.17.0; iapl-doctor warns) |
|
||
| `firstPaint` | `true` | banner in the server HTML, decided before the first paint; `false` = nothing until the page has hydrated (as before 1.17.0) |
|
||
| `nonce` | provider's | CSP nonce for the first-paint script; default: the one given to `ConsentProvider` / `SiteProviders` |
|
||
| `icon` | `true` | cookie icon |
|
||
| `order` | `['settings', 'reject', 'accept']` | banner buttons; keep `'reject'` (a development warning and iapl-doctor say so when it is missing) |
|
||
| `settings` | `'inline'` | `'inline' \| 'modal' \| 'detailed'` |
|
||
| `controls` | `'checkbox'` | `'checkbox' \| 'switch'` |
|
||
| `settingsActions` | `['back', 'save']` | buttons under the categories (`'accept' \| 'back' \| 'reject' \| 'save'`) |
|
||
|
||
`CookieButton` props: `className` (replaces the default classes; position is then yours too),
|
||
`side` (`'left'` default or `'right'`), `avoid` (CSS selector, default `COOKIE_BUTTON_AVOID` =
|
||
`'footer, [role="contentinfo"]'`; `false` = never move). While the footer is on screen the button
|
||
moves up by its visible part (`bottomOverlap`), so it never covers footer links. Position tokens:
|
||
`--ipal-cookie-button-offset` (from the bottom, default `1rem`), `--ipal-cookie-button-inset` (from the
|
||
side, default `1rem`); z-index `--ipal-z-header`. Type `CookieButtonProps`.
|
||
|
||
## Compliance defaults (1.17.0)
|
||
|
||
What the plugin now does with no project setting, each with its opt-out. Where the rules come from, and which are
|
||
law, regulator guidance or vendor policy: [dev/consent-compliance-proposal.md](./dev/consent-compliance-proposal.md).
|
||
The behaviour both IAPL and IAWL follow: [consent-behaviour-spec.md](./consent-behaviour-spec.md).
|
||
|
||
| Default | Opt-out |
|
||
|---|---|
|
||
| Global Privacy Control honoured (below) | `gpc="ask"` or `gpc={false}` on `SiteProviders` / `ConsentProvider` |
|
||
| "Reject" styled like "Accept all" (`equalChoice`) | `<CookieBanner equalChoice={false} />` |
|
||
| Consent log on (`consent-records`, posted by `SiteProviders`) | `iapl({ consentLog: false })`, or `logEndpoint={false}` on one layout |
|
||
| Withdrawal tells the running tools (Meta, TikTok, Clarity) and removes listed storage keys | none needed (a fix); `signalVendors` is exported for your own banner |
|
||
| Clarity gets its consent signal (`consentv2`) when it loads | — (Clarity needs one for EEA visits since 31 October 2025) |
|
||
| `ads_data_redaction` with the Consent Mode default | — (it acts only while `ad_storage` is denied) |
|
||
| Default text: "You can change your choice at any time with the cookie button, and set cookie rules in your browser too." | your own text in Cookies → *Banner* → message (the default is used only when it is empty) |
|
||
|
||
Not changed: Consent Mode stays `'advanced'` by default (the Google tag loads before a choice with every signal
|
||
`denied` and sends cookieless pings — [analytics.md](./analytics.md#how-consent-mode-works)); `'basic'` is the option for
|
||
"no request to Google before consent". The re-ask period stays 180 days (`maxAgeDays` to change it).
|
||
|
||
### Global Privacy Control (1.17.0)
|
||
|
||
Global Privacy Control ([W3C draft](https://www.w3.org/TR/gpc/)) is a browser setting that says "do not sell or
|
||
share my data": the browser sends `Sec-GPC: 1` and exposes `navigator.globalPrivacyControl === true`. Brave and
|
||
DuckDuckGo send it by default, Firefox on request and in private windows; Chrome and Safari are adding a setting.
|
||
In the EU it has no binding force of its own today (in California and eleven more US states it must be honoured);
|
||
optional categories are off until opt-in anyway, so the plugin reads it as a **refusal of analytics and marketing
|
||
that the visitor did not have to click**, and a choice the visitor makes on the site wins.
|
||
|
||
| Stored choice | Signal | `gpc: 'honour'` (default) |
|
||
|---|---|---|
|
||
| none | on | no banner (decided before the first paint), the cookie button; analytics and marketing off; **no request to Google** (also in Consent Mode `advanced`) or a pixel; nothing stored |
|
||
| made with the signal on (`gpc: true` in the record) | on | the choice stands, also a grant — the visitor chose it for this site |
|
||
| made without the signal (`gpc: false`) that granted analytics or marketing | on | both switched off without asking: cookies and listed storage keys deleted, the tools and Google told, the record rewritten (`gpc: true`) and posted to the consent log |
|
||
| from before 1.17.0 (no `gpc` field) | on | stands until it expires or the visitor changes it |
|
||
| any | off | stands — the absence of the signal is never consent |
|
||
|
||
`functional` is not the signal's business (no data is shared): a functional grant stays; with no choice it is off,
|
||
as for everyone. In the settings window (cookie button) a line says the signal is honoured
|
||
(`texts.gpcNotice`, filled by `getConsentTexts` in Polish or English; `classNames.gpcNotice`); "Accept all" or a
|
||
saved category there is the visitor's own choice and is stored with `gpc: true`.
|
||
|
||
- `gpc="ask"`: the banner is shown as usual (with the line); until a choice nothing is sent to any tracker, Google
|
||
included. `gpc={false}`: the signal is ignored (before 1.17.0) — iapl-doctor warns.
|
||
- **Static pages stay static.** The signal is read in the browser — by the first-paint script
|
||
(`consentBannerScript({ gpc })`) and the consent store — never while rendering a page: the HTML is the same with
|
||
and without it, and no `Vary` is needed. In server-read mode (`consentCookie`) a visitor with no stored choice
|
||
still gets the hidden banner and the script, because the server cannot know the signal.
|
||
- **On the server**, where a response is per visitor anyway: `gpcFromHeaders(headers)` (`Sec-GPC: 1` exactly). The
|
||
statistics endpoint uses it: a visitor id is not accepted while the signal overrides a choice made without it.
|
||
Reading the header in a layout makes the page dynamic; a cached response that differs by it needs
|
||
`Vary: Sec-GPC` (many CDNs then refuse to cache or need a rule) — so don't.
|
||
- **Building blocks:** `resolveConsent(record, signal, mode)` (pure, the table above), `gpcFromNavigator()`,
|
||
`gpcFromHeaders()`, `GPC_CATEGORIES`, `GPC_HEADER`, types `GpcMode`, `ResolvedConsent` (all `@intecion/ipal-kit`);
|
||
`readEffectiveConsent(version, mode)` from `/client` (the stored choice with the signal applied, read live —
|
||
for your own tag loader).
|
||
- **The site statement** `/.well-known/gpc.json` (optional): `app/.well-known/gpc.json/route.ts` with
|
||
`export const GET = gpcWellKnown({ lastUpdate: '2026-11-26' })` (`@intecion/ipal-kit`). The proxy's matcher
|
||
usually skips paths with a dot; if yours does not, let this path through.
|
||
- Do Not Track is not read (retired by the W3C; removed from Firefox). A site should never *state* that it ignores
|
||
browser signals (a German court treated DNT as a valid objection).
|
||
|
||
### Withdrawal stops what already runs (1.17.0)
|
||
|
||
When a category goes from on to off (the visitor reopens the settings, or GPC overrides an old grant):
|
||
|
||
- its cookies are deleted — the built-in list (`DEFAULT_COOKIE_MAP`), `cookieMap`, and the panel's cookie list
|
||
(Cookies → *Cookie list*, rows of that category), on this host and every parent domain;
|
||
- its **browser storage keys** from the panel's cookie list (rows of type *Local storage* / *Session storage*,
|
||
`name*` = prefix) are removed; necessary rows never;
|
||
- the tools already running are told: Meta Pixel `fbq('consent', 'revoke')`, TikTok `ttq.revokeConsent()`,
|
||
Clarity `clarity('consent', false)` (stops and erases its cookies); granting again on the same page sends
|
||
`grant` / `consentv2`. LinkedIn Insight has no such call: it stops with the next page load. Google gets the
|
||
Consent Mode update as before. Building blocks: `signalVendors(prev, next)`, `clarityConsent(state)` (`/client`).
|
||
|
||
## First paint: the banner is part of the first render (1.17.0)
|
||
|
||
Before 1.17.0 the banner rendered nothing until React had hydrated the page and an effect had read the
|
||
cookie. On a first visit its text appeared seconds after the page (measured on the reference site,
|
||
mobile profile with 4x CPU and slow 4G: page painted at 1.0 s, banner at 2.7 s) and on a text page it
|
||
became the **LCP element**. Now it is in the HTML and painted with the page (banner at 1.0 s, LCP 1.0 s).
|
||
An existing site gets this by updating: no edit, pages stay static.
|
||
|
||
**How (default, pages stay static / ISR / CDN-cached).** The HTML is the same for every visitor, so it
|
||
cannot know the visitor's cookie. The server renders the banner with the `hidden` attribute and, right
|
||
after it, one small inline script (`consentBannerScript`, about 0.6 kB). The script runs while the HTML is
|
||
parsed, before the browser paints:
|
||
|
||
| Visitor | Before the first paint | After hydration |
|
||
|---|---|---|
|
||
| no decision; decision under an older **Policy version**; unreadable or foreign `cookie-consent` | `hidden` removed → banner painted with the page | the same element becomes live (no re-render, no shift: the bar is `position: fixed`) |
|
||
| current decision | `display: none` on the banner → never painted | React removes it; `CookieButton` appears |
|
||
| no decision, browser sends Global Privacy Control (`gpc: 'honour'`, default) | `display: none` → never painted | React removes it; `CookieButton` appears |
|
||
| JavaScript off, or a CSP refused the script | banner stays hidden | with JS: appears after hydration, as before 1.17.0; without JS: no banner (and no tag: every tag is loaded by JS) |
|
||
|
||
The script decides exactly as `readConsentRecord` does, reads only the consent cookie, stores nothing and
|
||
loads nothing. A click on a banner button **before** hydration is not lost: the script notes the button
|
||
(`data-ipal-pending`), and the banner carries the click out when it becomes live (the decision, the cookie
|
||
and the consent log entry are made then, by the same code as any click). There is no hydration warning:
|
||
React hydrates with "no decision" (what the server rendered) and switches to the browser's own value
|
||
before the next paint (`useSyncExternalStore`).
|
||
|
||
What does **not** change: what counts as consent, when tags load (nothing earlier), the Consent Mode
|
||
default (still pushed first), the cookie (`cookie-consent`, `{ id, state, timestamp, version }`, plus `gpc`), the
|
||
consent log, withdrawal, `CookieButton`, the settings window in all three modes, texts per language.
|
||
|
||
**CSP.** With the header-only policy (`buildSecurityHeaders`, `'unsafe-inline'` for scripts — what
|
||
static pages need anyway) nothing is to be done. With a nonce policy (`createProxy({ csp })`) the script
|
||
needs the nonce: `<SiteProviders nonce={nonce}>` passes it on (a site that already passes `nonce` for the
|
||
theme script is done); by hand: `<ConsentProvider nonce={nonce}>` or `<CookieBanner nonce={nonce}>`.
|
||
Without the nonce the script is refused and the banner appears after hydration, as before.
|
||
|
||
**Your own `classNames.root`.** The banner is hidden with the `hidden` attribute. Tailwind 4 makes
|
||
`[hidden]` win over every utility; with Tailwind 3 (or other CSS) a root class that sets `display`
|
||
(`flex`, `grid`) overrides it: add `[data-ipal="banner"][hidden] { display: none !important }` to the
|
||
site's CSS.
|
||
|
||
**Turn it off:** `<CookieBanner firstPaint={false} />` — nothing in the HTML, the banner appears after
|
||
hydration (before 1.17.0).
|
||
|
||
**Option: read the cookie on the server (exact HTML, dynamic pages).** Pass the request's cookie and the
|
||
server render already knows the decision — no banner in the HTML for a visitor who decided (the
|
||
`CookieButton` instead), the banner without `hidden` and without a script for one who has not:
|
||
|
||
```tsx
|
||
import { CONSENT_COOKIE } from '@intecion/ipal-kit'
|
||
import { cookies } from 'next/headers'
|
||
|
||
const consentCookie = (await cookies()).get(CONSENT_COOKIE)?.value ?? null // null = read, none sent
|
||
<SiteProviders shell={shell} consentCookie={consentCookie}>… // by hand: <ConsentProvider cookieValue={consentCookie}>
|
||
```
|
||
|
||
The price: `cookies()` makes every page under that layout **dynamic** — rendered per request, no static
|
||
or ISR copy, and a CDN must not share one HTML between visitors. Choose it only for a site that is
|
||
dynamic anyway (a nonce CSP, signed-in pages). `undefined` (the prop left out) = static mode.
|
||
|
||
| | Static (default) | Server read (`consentCookie`) |
|
||
|---|---|---|
|
||
| Public pages | static / ISR, one HTML for all, CDN-cacheable | dynamic, per request |
|
||
| Banner in the HTML of a visitor who decided | yes, hidden before paint | no |
|
||
| Inline script | one (needs the nonce under a nonce CSP) | none |
|
||
| Banner at first paint for a new visitor | yes | yes |
|
||
|
||
**Your own banner** (AGENT.md §7 says: don't; when you must): `consentBannerScript({ version })` from
|
||
`@intecion/ipal-kit` (options: `ConsentBannerScriptOptions` — `version`, `cookieName`, `gpc`) is the same script — put `hidden` and `suppressHydrationWarning` on your banner's root and
|
||
the script in a `<script>` as its next sibling; `useConsentContext()` gives `hydrated` (false in the
|
||
server render and while hydrating) and `serverRead`.
|
||
|
||
## Overriding the look (Level 2)
|
||
|
||
The default Tailwind classes can be overridden with `classNames`:
|
||
|
||
```tsx
|
||
<CookieBanner classNames={{
|
||
root: 'fixed inset-x-0 bottom-0 ...', // your layout
|
||
primaryButton: 'btn btn-primary', // e.g. DaisyUI
|
||
secondaryButton: 'btn btn-ghost',
|
||
}} />
|
||
```
|
||
|
||
## Gating scripts by consent
|
||
|
||
```ts
|
||
import { updateConsent, setDefaultConsent } from '@intecion/ipal-kit'
|
||
// sends signals to Google Consent Mode (gtag) based on the consent state
|
||
```
|
||
|
||
The logic (categories, storage, parsing) is also available server-safe from
|
||
`@intecion/ipal-kit`:
|
||
|
||
```ts
|
||
import { parseConsent, CONSENT_COOKIE, CONSENT_CATEGORIES } from '@intecion/ipal-kit'
|
||
// e.g. server-side script gating based on the consent cookie
|
||
```
|
||
|
||
### ConsentScript — load a script only after consent
|
||
|
||
For third parties WITHOUT their own Consent Mode (Meta Pixel, LinkedIn Insight, chats,
|
||
your own analytics) use `ConsentScript` — it loads the script only after consent for
|
||
its category and reacts live (accept in the banner → the script appears without a
|
||
reload). Render it inside `<ConsentProvider>`:
|
||
|
||
```tsx
|
||
import { ConsentScript } from '@intecion/ipal-kit/client'
|
||
|
||
<ConsentScript category="marketing" src="https://connect.facebook.net/en_US/fbevents.js" />
|
||
<ConsentScript category="marketing" code={`fbq('init','123');fbq('track','PageView')`} />
|
||
<ConsentScript category="analytics"
|
||
src="https://plausible.io/js/script.js"
|
||
attributes={{ 'data-domain': 'example.com' }} />
|
||
```
|
||
|
||
GA/GTM are better handled by Consent Mode (`updateConsent` above) — `ConsentScript` is
|
||
for vendors you cannot gate that way. Note: a script once loaded runs until the page
|
||
ends (a `<script>` tag cannot be "unloaded") — withdrawing consent blocks the NEXT
|
||
load; for running tags rely on Consent Mode.
|
||
|
||
## Look — overriding styles
|
||
|
||
The banner and the button have a default, neutral look (light + dark) and work
|
||
without any configuration. Colours and radii are the site's design tokens
|
||
([design-tokens.md](./design-tokens.md)): with `@intecion/ipal-kit/tokens.css` and the brand's
|
||
`src/design/tokens.ts` the banner follows the brand in both themes on its own. Without them, declare the
|
||
variables in your CSS. No imports, no props, no fighting specificity:
|
||
|
||
```css
|
||
/* global.css — everything optional, override only what you want */
|
||
:root {
|
||
--ipal-primary: #16a34a;
|
||
--ipal-primary-hover: #15803d;
|
||
--ipal-radius: 1rem;
|
||
}
|
||
```
|
||
|
||
Tokens the banner reads (1.15.0: the single names, which switch with the theme in `tokens.css`; without
|
||
`tokens.css` the fallback below follows the page's `color-scheme` via `light-dark()`, and a `-dark` variable a
|
||
site still sets — e.g. `--ipal-surface-dark` — is used as the dark fallback):
|
||
|
||
| Token | Default | What it colours |
|
||
|---|---|---|
|
||
| `--ipal-surface` | `#fff` | banner and button background |
|
||
| `--ipal-border` | `#e5e5e5` | borders |
|
||
| `--ipal-text` | `#404040` | body text |
|
||
| `--ipal-text-strong` | `#171717` | headings, category names |
|
||
| `--ipal-text-muted` | `#737373` | category descriptions |
|
||
| `--ipal-primary` | `#2563eb` | primary button, icon, link, checkbox |
|
||
| `--ipal-primary-hover` | `#1d4ed8` | primary button hover |
|
||
| `--ipal-primary-text` | `#fff` | text on the primary button |
|
||
| `--ipal-hover` | `#f5f5f5` | secondary buttons hover |
|
||
| `--ipal-radius` | `0.375rem` | button radius |
|
||
|
||
Requires an `@source` that scans the package (see PROGRAMISTA.md §2.5) — otherwise
|
||
Tailwind will not generate these classes.
|
||
|
||
### When tokens are not enough
|
||
|
||
Layout (spacing, position, breakpoints) is not tokenized — it is not something
|
||
that changes per brand, and exposing it would mean reinventing CSS, variable by
|
||
variable. For bigger changes there is `classNames`:
|
||
|
||
```tsx
|
||
<CookieBanner classNames={{
|
||
root: 'fixed inset-0 z-50 grid place-items-center bg-black/50', // modal instead of a bar
|
||
primaryButton: 'btn btn-primary', // e.g. DaisyUI
|
||
secondaryButton: 'btn btn-ghost',
|
||
}} />
|
||
<CookieButton className="fixed bottom-6 right-6 ..." />
|
||
```
|
||
|
||
A given className replaces the default (it is not appended). Every element has its own slot (1.10.0):
|
||
|
||
| Slot | Element |
|
||
|---|---|
|
||
| `root`, `body`, `content` | bar, inner width, text + buttons row |
|
||
| `text`, `icon`, `eyebrow`, `title`, `message`, `link` | banner text block |
|
||
| `actions` | banner buttons row |
|
||
| `primaryButton`, `secondaryButton` | two button styles (defaults for all) |
|
||
| `acceptButton`, `rejectButton`, `settingsButton`, `saveButton`, `backButton` | single buttons — empty → `primaryButton` / `secondaryButton` |
|
||
| `overlay`, `dialog`, `closeButton` | settings modal (`settings="modal"` / `"detailed"`) |
|
||
| `categoryCard`, `cookies`, `cookiesToggle`, `cookieList`, `cookie`, `cookieName`, `cookieMeta` | large window (`settings="detailed"`): category card, expandable cookie list, one cookie, name, provider / purpose / duration grid |
|
||
| `settingsTitle`, `settingsDescription`, `categories`, `category`, `categoryTitle`, `categoryDescription` | settings view |
|
||
| `control`, `controlThumb`, `badge` | checkbox / switch, switch thumb, "Always active" badge |
|
||
| `settingsActions` | buttons row under the categories |
|
||
|
||
### Layout: button order, modal, switches (1.10.0)
|
||
|
||
```tsx
|
||
<CookieBanner
|
||
equalChoice
|
||
icon={false} // no cookie icon
|
||
order={['accept', 'reject', 'settings']} // banner buttons in this order
|
||
settings="modal" // settings in a centred window (✕, Escape, click on backdrop)
|
||
controls="switch" // role="switch" toggles instead of checkboxes
|
||
settingsActions={['save', 'reject', 'accept']} // buttons under the categories
|
||
classNames={{ … }}
|
||
/>
|
||
```
|
||
|
||
By default (without these props) the banner looks and works as before 1.10.0.
|
||
|
||
### Large window with details (`settings="detailed"`, 1.12.3)
|
||
|
||
Three settings modes to pick in the project — one prop:
|
||
|
||
| `settings` | What the user sees after "Settings" |
|
||
|---|---|
|
||
| `'inline'` (default) | categories inside the banner bar |
|
||
| `'modal'` | small centred window: category + short description + switch |
|
||
| `'detailed'` | large window: each category is a card with a switch, a description and an expandable list of its cookies (name, provider, purpose, retention) |
|
||
|
||
```tsx
|
||
<CookieBanner equalChoice controls="switch" settings="detailed" />
|
||
```
|
||
|
||
The cookie list comes from **Cookies → Cookie list** (the same source as `<CookieTable>` on the policy
|
||
page), filtered by category — a category without entries has no expandable list. List labels: **Cookie
|
||
Settings → Detail labels** (`cookies` — e.g. "Cookies used", the counter is added automatically; `provider`,
|
||
`purpose`, `duration`), per language; empty → English. `getConsentTexts` passes this in `texts.cookies` /
|
||
`texts.details` — nothing to pass in code. Closing as in `'modal'` (✕, Escape, click on backdrop). Default
|
||
window width `max-w-4xl` — change it with `classNames.dialog`.
|
||
|
||
Which mode to choose: the project design decides. If the brief is silent → `'detailed'` (at the moment of
|
||
consent the user sees which cookies are set and by whom — full information where the decision is made),
|
||
provided the Cookies list is filled from a scan (`iapl({ cookieScanner: true })` → *Cookie review* → **Scan cookies** → *Approve cookies* → **Approve and add**,
|
||
[cookie-scanner.md](./cookie-scanner.md), or `iapl-consent-check` → cookie-scan); an empty list = a
|
||
window without expandable lists, then `'modal'` is enough. Record the decision in `AGENTS.md` →
|
||
"Project decisions".
|
||
|
||
Recommendation (AGENT.md §7): tokens and `classNames` first — then fixes from plugin updates reach the
|
||
project. When you need a completely different layout, you can build your own window; the data is in the
|
||
context: `useConsentContext()` → `texts.cookies`, `texts.details`, `state`, `savePreferences`.
|
||
|
||
Texts from the panel (**Cookies**, per language) — empty field = the element is not shown:
|
||
|
||
| Field | Where |
|
||
|---|---|
|
||
| `eyebrow` | small label above the banner title ("Privacy and cookies") |
|
||
| `title` | banner title ("We respect your privacy") |
|
||
| `settingsDescription` | description under the settings title |
|
||
| `alwaysActiveLabel` | badge next to "Necessary" instead of a disabled switch |
|
||
| `detailLabels.cookies` / `.provider` / `.purpose` / `.duration` | cookie list labels in the `settings="detailed"` window (empty → English) |
|
||
| `cookies` (list) | cookies per category — the `detailed` window and `<CookieTable>`; `purpose`, `duration` per language |
|
||
| `buttons.close` | screen-reader label of the ✕ button (empty → "Close") |
|
||
| `buttons.savePreferences` | "Save" in the settings (up to 1.11.0 the field was `save` — a name reserved in Mongoose; in code still `texts.buttons.save`). MongoDB: since 1.12.2 the plugin copies the old `save` (all languages) on startup when `savePreferences` is missing |
|
||
|
||
New fields in the global = a migration in projects on Postgres/SQLite (`payload migrate:create`); MongoDB unchanged.
|
||
|
||
The elements also have stable `data-ipal` handles for CSS and e2e tests (used by
|
||
`iapl-consent-check`): `banner` (while it waits for the first-paint script it carries `hidden`; a button clicked before hydration:
|
||
`data-ipal-pending`; live: `data-ipal-ready`), `banner-script`, `cookie-button` and the buttons `settings`, `reject`,
|
||
`accept`, `back`, `save`; in modal mode also `consent-overlay`, `consent-dialog`, `close`; in detailed mode
|
||
additionally `category-<category>` (card) and `cookies` (expandable list).
|
||
|
||
Accessibility: the banner dialog and `CookieButton` have an `aria-label` from **Cookies →
|
||
title** or **settingsTitle** (per language) — no hard-coded texts in the components. The modal has
|
||
`aria-modal`, focus on ✕ after opening and closes on Escape; switches have `role="switch"` and `aria-checked`.
|
||
|
||
## Locale as a functional cookie (built in)
|
||
|
||
The plugin itself manages one functional cookie: **`NEXT_LOCALE`** (language choice).
|
||
You do not need to configure anything — it works out of the box:
|
||
|
||
- **Stored only with consent.** The middleware writes `NEXT_LOCALE` only when the user
|
||
has accepted the **functional** category. Without consent the language still works
|
||
(negotiated per request), but it is not persisted in a cookie. The middleware/proxy
|
||
option `consentCategory: 'necessary'` always writes it.
|
||
By default the middleware accepts a stored consent under the policy version it was
|
||
saved with (the proxy cannot read the panel). To require the current *Policy version*,
|
||
pass `policyVersion` to the middleware/proxy (`createLocaleMiddleware` / `createProxy`).
|
||
- **Cleanup after withdrawal.** When the user withdraws functional consent, the consent
|
||
hook deletes `NEXT_LOCALE` automatically. `DEFAULT_COOKIE_MAP` is responsible for that:
|
||
|
||
```ts
|
||
const DEFAULT_COOKIE_MAP = {
|
||
analytics: ['_ga', '_ga_*', '_gid', '_gat*', '_clck', '_clsk', 'CLID', '_hj*', 'ipal_vid'], // ipal_vid — stats.md
|
||
functional: [LOCALE_COOKIE_NAME], // 'NEXT_LOCALE' — the plugin knows its own cookie
|
||
marketing: ['_fbp', '_fbc', '_gcl_*', '_ttp', 'li_fat_id', '_uetsid', '_uetvid'],
|
||
}
|
||
```
|
||
|
||
### Your own functional/analytics cookies
|
||
|
||
If you set your own cookie that is subject to consent, add it through `cookieMap` —
|
||
after consent is withdrawn it is deleted together with the defaults:
|
||
|
||
```tsx
|
||
<ConsentProvider texts={texts} cookieMap={{ functional: ['my-setting'], analytics: ['_my*'] }}>
|
||
```
|
||
|
||
The map is **added** to `DEFAULT_COOKIE_MAP` (it does not replace it), `*` at the end
|
||
= prefix. `SiteProviders cookieMap` and `useConsent({ cookieMap })` take the same
|
||
(low-level hook — in the app use the provider, otherwise you get a second,
|
||
independent consent state).
|
||
|
||
> The consent mechanism for the locale is also described from the i18n side:
|
||
> [i18n.md](./i18n.md#locale-cookie-and-consent-gdpr).
|
||
|
||
## Cookies and browser storage in one list (type)
|
||
|
||
*Cookies → Cookie list* holds cookies **and** keys the site keeps in the browser's local or session
|
||
storage (the theme choice, a chat widget's state). Each row has a **Type** (`storage`: `cookie` ·
|
||
`localStorage` · `sessionStorage`, default `cookie`, shared by every language). The cookie scanner fills it.
|
||
|
||
| Where | What visitors see |
|
||
|---|---|
|
||
| `<CookieTable>` (`/rsc`) | a **Type** column when the list has an entry that is not a cookie (`storageColumn: 'auto'`, the default; `true` / `false` to force it). Column heading `labels.storage`, type names `storageTypes` — defaults per `locale`: en *Type* · *Cookie* / *Local storage* / *Session storage*, pl `Rodzaj` · `Plik cookie` / `Pamięć lokalna` / `Pamięć sesji` (`COOKIE_STORAGE_LABELS`) |
|
||
| Detailed settings window | a **Type** line under entries that are not cookies: label from *Settings window → Cookie list headings → Type* (empty = default per language), type names from `texts.details.storageTypes` |
|
||
| `getCookieTable` / `texts.cookies` | every row has `storage` (`ConsentStorage`); `texts.details.storage` / `.storageTypes` |
|
||
|
||
**Migration (Postgres / SQLite):** two added columns, nothing dropped — `cookie_settings_cookies.storage`
|
||
(enum, `DEFAULT 'cookie'`, so existing rows become *Cookie*) and `cookie_settings_locales.detail_labels_storage`.
|
||
Run `pnpm payload migrate:create cookie-storage-type` and commit it. Change the type of existing storage rows
|
||
by hand (a scan fills it only for new rows).
|
||
|
||
## Every language filled (`fillEmptyLocales`)
|
||
|
||
The cookie list's **Purpose** and **Duration** are per language. Text an editor writes in one language
|
||
is copied to every language where that field is still empty, when the document is saved — a cookie
|
||
added in Polish is not blank on the English page. A language that already has its own text is never
|
||
overwritten, so each language can still be changed on its own. The same applies to the cookie review
|
||
entries (purpose, duration). Cookie scanner and approval writes do the same with their own texts:
|
||
English and Polish where they exist, the default language's text for any other language.
|
||
|
||
Payload's `localization.fallback` covers only part of this: an empty language *reads* as the default
|
||
language's text, but nothing is stored, the admin shows the field empty, and the text always comes
|
||
from the default language, not from the one just edited.
|
||
|
||
| Option | Default | |
|
||
|---|---|---|
|
||
| `fillEmptyLocales` | `true` | `false` = off; `{ 'cookie-settings': ['cookies.purpose'], 'cookie-review': [] }` = choose the fields per slug (`[]` = off for that slug). Field paths: `'field'` or `'arrayField.subField'` |
|
||
|
||
Building blocks for your own globals and collections (`@intecion/ipal-kit`):
|
||
`buildFillEmptyLocalesGlobalHook({ global, fields })`, `buildFillEmptyLocalesCollectionHook({ collection, fields })`
|
||
(afterChange hooks), `fillEmptyLocales({ payload, target, source, sourceLocale, fields, req? })` (the
|
||
core, `FillEmptyLocalesTarget` = `{ global }` or `{ collection, id }`), and `withFillLocales(kind, config, fields)`
|
||
to add the hook to a config. Nothing to migrate.
|
||
|
||
## Policy version, withdrawing consent, consent log, cookie table (1.9.1)
|
||
|
||
- **New consent after a policy change:** Cookies → *Consent version* (sidebar). Raise it by 1
|
||
after adding a tool or changing the policy — every visitor will see the banner again.
|
||
`getConsentTexts` passes the version to `<ConsentProvider texts>` automatically.
|
||
- **Withdrawing consent deletes the tools' cookies** (`_ga`, `_ga_*`, `_gid`, `_fbp`, `_gcl_*`, Clarity,
|
||
LinkedIn, TikTok, Hotjar…) — also on the parent domain (`.client.com`), where GA stores them.
|
||
The project's own cookies: `<ConsentProvider cookieMap={{ marketing: ['_my*'] }}>` (added to the
|
||
default list, `*` = prefix).
|
||
- **Equal choice:** "Reject" looks like "Accept all" — **the default since 1.17.0** (`equalChoice={false}`
|
||
restores the secondary look). This is the position of the EU data-protection authorities (EDPB Cookie Banner
|
||
Taskforce report, 2023: no reject option on a layer that has a consent button is an infringement for a vast
|
||
majority of them; colours are judged case by case), repeated in a UODO article (2025); it is regulator guidance,
|
||
not a statute, and no UODO or UKE decision on a banner was found.
|
||
- **Consent log (proof of consent, GDPR Art. 7(1)):** **on by default since 1.17.0**;
|
||
`iapl({ consentLog: { retentionDays: 730 } })` to change it, `consentLog: false` to turn it off.
|
||
`SiteProviders` posts every decision there by itself (`shell.consentLogEndpoint`); a hand-wired
|
||
`<ConsentProvider>` needs `logEndpoint="/api/ipal/consent"`. It stores a random identifier (the same as in the
|
||
cookie), the choices, the policy version and the time — **no IP and no user agent**. *Consent records*
|
||
collection (admin only), automatic cleanup after `retentionDays` (default 1095). Details below.
|
||
**Postgres / SQLite: a new table** — [create and apply a migration](#postgres-sqlite-the-consent-log-is-a-table).
|
||
- **Cookie table** for the policy page: Cookies → *Cookie list* + `getCookieTable` + `<CookieTable>` from `/rsc`.
|
||
Fill the list from the panel with the cookie scanner (`cookieScanner` option — one approval adds every cookie found to the list, the table and the detailed window,
|
||
[cookie-scanner.md](./cookie-scanner.md)) and check the real site with `iapl-consent-check` → cookie-scan.
|
||
- Consent cookie: `cookie-consent` (`CONSENT_COOKIE`), JSON `{ id, state, timestamp, version }`,
|
||
`max-age` 180 days (`CONSENT_MAX_AGE`; `maxAgeDays` changes it), `samesite=lax`, `Secure` on HTTPS. Since 1.17.0
|
||
the record may carry `gpc` (was the signal on when the choice was made). Consent with another
|
||
policy version is treated as no decision.
|
||
- Global Privacy Control: honoured by default since 1.17.0 — [above](#global-privacy-control-1170).
|
||
|
||
## Consent log — details (`consentLog`)
|
||
|
||
| Item | Value |
|
||
|---|---|
|
||
| Option | `consentLog?: boolean \| { retentionDays?: number; collectionOverrides?: CollectionOverride }` (type `ConsentLogOptions`) |
|
||
| `retentionDays` | default `1095` (3 years) |
|
||
| `collectionOverrides` | changes `consent-records`: an object merges `access` / `admin` / `hooks` key by key (your keys win), other keys replace; a function `(collection) => collection` takes over (keep the slug — the endpoint writes to it) |
|
||
| Collection | `consent-records` (`CONSENT_LOG_SLUG`), group *Privacy*; fields `consentId` (index), `version`, `choices.{necessary,functional,analytics,marketing}`, `createdAt` |
|
||
| Collection access | `read` / `delete` — admin (without `access`, i.e. no roles: any logged-in account — narrow it with `collectionOverrides`); `create` / `update` — nobody through the API (written only by the endpoint, `overrideAccess`) |
|
||
| Endpoint | `POST /api/ipal/consent`, public (no login) |
|
||
| Default | on (since 1.17.0); `consentLog: false` = no collection, no endpoint, `shell.consentLogEndpoint` null |
|
||
| Body | `{ id: string (hex 16–64), version: int ≥ 1, state: { necessary, functional, analytics, marketing: boolean }, gpc?: boolean }` (`gpc` is accepted and not stored) |
|
||
| Responses | `201 { ok: true }`, `400` (bad JSON/validation), `429` (limit 20 requests/min per IP, scope `consent`), `503` (the table does not exist: one log line per server start), `500` |
|
||
| Cleanup | on a write, at most once per 24 h per process: one `db.deleteMany` for records older than `retentionDays`, **in the background** (the consent write does not wait; an error is logged and the cleanup is retried on the next write) |
|
||
|
||
The provider sends a record after every decision (`fetch` with `keepalive`, errors ignored —
|
||
the banner never waits). By hand: `buildConsentLogCollection()` / `buildConsentLogEndpoint(opts)`
|
||
from `@intecion/ipal-kit`; `CONSENT_LOG_PATH` is the endpoint's path under the API route (`/ipal/consent`).
|
||
|
||
### Postgres / SQLite: the consent log is a table
|
||
|
||
On MongoDB the collection appears by itself. On a SQL database `consent-records` is a table, so the deploy that
|
||
brings 1.17.0 to a project that never had `consentLog` on must create it — **in the same deploy**, before the new
|
||
version serves requests. The migration Payload generates (checked on Postgres 16 and SQLite) creates one table,
|
||
`consent_records` (the choices are its columns, three indexes), and adds one column, `consent_records_id`, with its
|
||
index and foreign key to Payload's own `payload_locked_documents_rels`; it drops nothing:
|
||
|
||
```bash
|
||
pnpm payload migrate:create consent-log # commit the file in src/migrations/
|
||
pnpm payload migrate # applied at container start (prodMigrations, or `pnpm payload migrate && pnpm start`)
|
||
```
|
||
|
||
Or `iapl({ consentLog: false })` when the project does not want the log. Without the table nothing breaks: the page
|
||
and the banner work, each choice answers `503` and the server logs once *"the consent-records table does not
|
||
exist — create and apply a migration…"*; `iapl-doctor` reports `consent-log-migration` as an error while no
|
||
migration in `src/migrations` creates `consent_records`.
|
||
|
||
Narrow who reads the records (e.g. a project without roles, only the data protection officer):
|
||
|
||
```ts
|
||
iapl({
|
||
consentLog: {
|
||
collectionOverrides: { access: { read: ({ req }) => req.user?.email === '[email protected]' } },
|
||
},
|
||
})
|
||
```
|
||
|
||
## Turn off, override, extend
|
||
|
||
- **Turn off:** do not mount `CookieBanner` / `CookieButton` (or `SiteProviders banner={false}
|
||
cookieButton={false}`). The `cookie-settings` global is currently always added (no option to drop
|
||
it); the consent log with `consentLog: false`; Global Privacy Control with `gpc={false}`.
|
||
- **Override:** texts and the cookie list in the panel; the look with `--ipal-*` tokens and `classNames`;
|
||
the layout with the props `order`, `settings`, `controls`, `settingsActions`, `equalChoice`, `icon`;
|
||
`gpc` and `maxAgeDays` on the provider;
|
||
the log's `retentionDays`; `privacyPolicy` / `settingsSlug` in `getConsentTexts`. The `cookie-settings`
|
||
global (write access is `admin` + `editor` by default, hooks, admin options):
|
||
`iapl({ globalOverrides: { 'cookie-settings': { access: { update } } } })` — your access rules win,
|
||
your hooks run after the plugin's; a function gets the plugin's global and returns the one to use.
|
||
- **Cookie list from the panel:** `iapl({ cookieScanner: true })` — opt-in: scan, then one **Approve and add**
|
||
on the *Approve cookies* page puts every cookie found into the cookie list (and so into `<CookieTable>` and the
|
||
detailed window); `cookieScanner: { approval: false }` keeps per-entry review. See
|
||
[cookie-scanner.md](./cookie-scanner.md) (off, overrides and building blocks there).
|
||
- **Pre-consent check in a real browser:** `cookieScanner: { crawl: true }` + the shared scanner service
|
||
— **Check site** in the panel, violations (non-necessary cookies or trackers before consent), dashboard
|
||
warning, optional e-mail ([cookie-scanner.md → Browser crawl](./cookie-scanner.md#browser-crawl)).
|
||
- **Extend:** `cookieMap` (your own cookies to delete), `ConsentScript` (scripts without Consent
|
||
Mode), `useConsentContext()` (your own UI: `state`, `acceptAll`, `rejectAll`, `savePreferences`,
|
||
`reopen`, `texts`, `gpc`, `gpcMode`), server-safe helpers (`parseConsent`, `readConsentRecord`, `CONSENT_COOKIE`,
|
||
`getCookieTable`, `resolveConsent`, `gpcFromHeaders`) and the builders `buildConsentLogCollection` /
|
||
`buildConsentLogEndpoint`.
|