Files
ipal-kit/docs/consent.md
T
Radosław SmolińskiandClaude Opus 5.5 86ff3f5ff7 Cookie scanner: one approval for everything a scan finds
After "Scan cookies" or a site check, the new Approve cookies view
(/admin/cookie-approval) lists what waits, grouped by consent category, with
provider, purpose and duration and New / Changed / Needs description markers.
One "Approve and add" puts every ticked cookie into Cookie banner -> Cookie
list in every locale. That list feeds the cookie policy table and the
detailed settings window.

- Never overwrites editor text or categories, never adds a second row (a
  pattern and a concrete name are the same cookie), never deletes.
- Unknown cookies are approved into a category that needs consent
  (approval.unknownCategory, default marketing) and flagged Needs
  description; writing a purpose clears the flag.
- Cookies a scan or crawl no longer finds are flagged No longer found, for
  review only.
- The dashboard and the crawl e-mail say how many cookies wait and link to
  the view; nothing is added without approval.
- Optional: cookieScanner.approval false keeps per-entry review.
- Migration: cookie-review gains change and needsDescription.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-28 22:17:46 +01:00

22 KiB
Raw Blame History

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 ipal-kit; you add nothing in the project.

Config

The CookieSettings global (slug cookie-settings, group Settings) is always built. 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: ipalKit({ 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 Cookie banner → 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:

<SiteProviders shell={await getSiteShell(locale)} logEndpoint="/api/ipal/consent"
  banner={<CookieBanner equalChoice classNames={…} />}>{children}</SiteProviders>

SiteProviders also takes cookieMap, banner={false}, cookieButton={false} (or your own element) and analytics={false | { consentMode, defer, deferTimeoutMs }} (consentMode: 'basic' = no Google request before consent — see 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:

// 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 = Cookie banner → 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). CookieBanner does not render after a decision, CookieButton — the opposite (it shows only after a decision and reopens the banner); both render only after mounting on the client.

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 false "Reject" styled as the primary button
icon true cookie icon
order ['settings', 'reject', 'accept'] banner buttons
settings 'inline' 'inline' | 'modal' | 'detailed'
controls 'checkbox' 'checkbox' | 'switch'
settingsActions ['back', 'save'] buttons under the categories ('accept' | 'back' | 'reject' | 'save')

CookieButton takes only className (replaces the default).

Overriding the look (Level 2)

The default Tailwind classes can be overridden with classNames:

<CookieBanner classNames={{
  root: 'fixed inset-x-0 bottom-0 ...',   // your layout
  primaryButton: 'btn btn-primary',        // e.g. DaisyUI
  secondaryButton: 'btn btn-ghost',
}} />
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:

import { parseConsent, CONSENT_COOKIE, CONSENT_CATEGORIES } from '@intecion/ipal-kit'
// e.g. server-side script gating based on the consent cookie

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

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 go through CSS custom properties with fallbacks — to restyle for a client, declare the variables in your CSS. No imports, no props, no fighting specificity:

/* global.css — everything optional, override only what you want */
:root {
  --ipal-primary: #16a34a;
  --ipal-primary-hover: #15803d;
  --ipal-radius: 1rem;
}

Available tokens (each has a -dark counterpart used under dark:):

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:

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

<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)
<CookieBanner equalChoice controls="switch" settings="detailed" />

The cookie list comes from Cookie banner → 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 (ipalKit({ cookieScanner: true }) → Cookie review → Scan cookies → Approve cookies → Approve and add, cookie-scanner.md, or ipal-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 (Cookie banner, 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 ipal-consent-check): banner, 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 Cookie banner → 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.

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

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

  • New consent after a policy change: Cookie banner → 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: <CookieBanner equalChoice /> — "Reject" looks like "Accept all" (UODO/EDPB requirement: refusing must be as easy as consenting). Off by default so the look of existing sites does not change; turn it on in new projects.
  • Consent log (proof of consent, GDPR Art. 7(1)): ipalKit({ consentLog: true }) or ipalKit({ consentLog: { retentionDays: 730 } }) + <ConsentProvider logEndpoint="/api/ipal/consent"> (or SiteProviders logEndpoint). 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: migrate:create.
  • Cookie table for the policy page: Cookie banner → 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) and check the real site with ipal-consent-check → cookie-scan.
  • Consent cookie: cookie-consent (CONSENT_COOKIE), JSON { id, state, timestamp, version }, max-age 180 days (CONSENT_MAX_AGE), samesite=lax, Secure on HTTPS. Consent with another policy version is treated as no decision.
  • Global Privacy Control is not needed: in the EU everything except necessary is off by default anyway until consent.
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 Settings; 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)
Body { id: string (hex 16–64), version: int ≥ 1, state: { necessary, functional, analytics, marketing: boolean } }
Responses 201 { ok: true }, 400 (bad JSON/validation), 429 (limit 20 requests/min per IP, scope consent), 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.

Narrow who reads the records (e.g. a project without roles, only the data protection officer):

ipalKit({
  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 only with consentLog.
  • 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; the log's retentionDays; privacyPolicy / settingsSlug in getConsentTexts. The cookie-settings global (write access is admin + editor by default, hooks, admin options): ipalKit({ 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: ipalKit({ 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 (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).
  • Extend: cookieMap (your own cookies to delete), ConsentScript (scripts without Consent Mode), useConsentContext() (your own UI: state, acceptAll, rejectAll, savePreferences, reopen, texts), server-safe helpers (parseConsent, readConsentRecord, CONSENT_COOKIE, getCookieTable) and the builders buildConsentLogCollection / buildConsentLogEndpoint.