BespokeCodeDE

payload consent

by BespokeCodeDE
Other
v3
^3.40.0
MIT

Overview

Summary generated from the README

Adds consent categories, services and settings as Payload collections and a global, so editors manage cookie declarations in the admin. The frontend gets a themeable banner, settings dialog, consent-gated embeds and a script loader that keeps non-essential scripts out of the page until consent is given. Requires Payload 3.40+ and React 19, and Next.js 15 for the server-rendered provider.

Features

  • Consent categories, services and cookie declarations editable as Payload collections
  • Themeable banner, settings dialog and cookie table components
  • Script loader that injects tags only after the relevant category is granted
  • Google Consent Mode v2 signals and Global Privacy Control support
  • ConsentGate component for blocking iframes and widgets, including standalone gates
  • Optional consent logging collection and a public config endpoint

Use cases

  • Add a GDPR-style cookie banner to a Payload and Next.js site without an external consent platform
  • Hold back YouTube or booking widget embeds until a visitor consents
  • Publish a cookie declaration table in a privacy policy that matches the loaded services

From the author

Consent management for Payload CMS — cookie banner, script gating and cookie declarations, managed from within the admin panel.

Installation

npm i @bespokecode/payload-consent

3

Stars

0

Forks

0

Open Issues

4 months ago

Last Updated

146

Weekly Downloads

v1.0.2

npm Version

527.7 KB

Unpacked Size

0

Dependencies

GitHub stars

3+1 since Sep 7

Show data
GitHub stars by day (UTC)
DateStars
Dec 6, 20263
Dec 5, 20263
Dec 4, 20263
Dec 3, 20263
Dec 2, 20263
Dec 1, 20263
Nov 30, 20263
Nov 29, 20263
Nov 28, 20263
Nov 27, 20263
Nov 26, 20263
Nov 25, 20263
Nov 24, 20263
Nov 23, 20263
Nov 22, 20263
Nov 21, 20263
Nov 20, 20263
Nov 19, 20263
Nov 18, 20263
Nov 17, 20263
Nov 16, 20263
Nov 15, 20263
Nov 14, 20263
Nov 13, 20263
Nov 12, 20263
Nov 11, 20263
Nov 10, 20263
Nov 9, 20263
Nov 8, 20263
Nov 7, 20263
Nov 6, 20263
Nov 5, 20263
Nov 4, 20262
Nov 3, 20262
Nov 2, 20262
Nov 1, 20262
Oct 31, 20262
Oct 30, 20262
Oct 29, 20262
Oct 28, 20262
Oct 27, 20262
Oct 26, 20262
Oct 25, 20262
Oct 24, 20262
Oct 23, 20262
Oct 22, 20262
Oct 21, 20262
Oct 20, 20262
Oct 19, 20262
Oct 18, 20262
Oct 17, 20262
Oct 16, 20262
Oct 15, 20262
Oct 14, 20262
Oct 13, 20262
Oct 12, 20262
Oct 11, 20262
Oct 10, 20262
Oct 9, 20262
Oct 8, 20262
Oct 7, 20262
Oct 6, 20262
Oct 5, 20262
Oct 4, 20262
Oct 3, 20262
Oct 2, 20262
Oct 1, 20262
Sep 30, 20262
Sep 29, 20262
Sep 28, 20262
Sep 27, 20262
Sep 26, 20262
Sep 25, 20262
Sep 24, 20262
Sep 23, 20262
Sep 22, 20262
Sep 21, 20262
Sep 20, 20262
Sep 19, 20262
Sep 18, 20262
Sep 17, 20262
Sep 16, 20262
Sep 15, 20262
Sep 14, 20262
Sep 13, 20262
Sep 12, 20262
Sep 11, 20262
Sep 10, 20262
Sep 9, 20262
Sep 8, 20262
Sep 7, 20262
npm weekly downloads

146+130 since Sep 7

Show data
npm weekly downloads by day (UTC)
DateWeekly downloads
Dec 6, 2026146
Dec 5, 2026149
Dec 4, 2026164
Dec 3, 2026143
Dec 2, 2026117
Dec 1, 2026153
Nov 30, 2026155
Nov 29, 2026150
Nov 28, 2026146
Nov 27, 2026135
Nov 26, 2026139
Nov 25, 2026168
Nov 24, 2026115
Nov 23, 2026109
Nov 22, 202690
Nov 21, 2026123
Nov 20, 2026121
Nov 19, 2026116
Nov 18, 202691
Nov 17, 202687
Nov 16, 202686
Nov 15, 202694
Nov 14, 2026138
Nov 13, 2026262
Nov 12, 2026333
Nov 11, 2026412
Nov 10, 2026519
Nov 9, 2026551
Nov 8, 2026589
Nov 7, 2026532
Nov 6, 2026425
Nov 5, 2026368
Nov 4, 2026286
Nov 3, 2026241
Nov 2, 2026234
Nov 1, 2026197
Oct 31, 2026227
Oct 30, 2026236
Oct 29, 2026216
Oct 28, 2026207
Oct 27, 2026149
Oct 26, 2026124
Oct 25, 2026112
Oct 24, 202653
Oct 23, 202619
Oct 22, 202627
Oct 21, 202648
Oct 20, 202641
Oct 19, 202641
Oct 18, 202644
Oct 17, 202639
Oct 16, 202642
Oct 15, 202640
Oct 14, 202647
Oct 13, 202654
Oct 12, 202663
Oct 11, 202678
Oct 10, 202698
Oct 9, 2026101
Oct 8, 202698
Oct 7, 202678
Oct 6, 202674
Oct 5, 202664
Oct 4, 202666
Oct 3, 2026135
Oct 2, 2026143
Oct 1, 2026140
Sep 30, 2026141
Sep 29, 2026147
Sep 28, 2026146
Sep 27, 2026137
Sep 26, 202697
Sep 25, 202689
Sep 24, 202691
Sep 23, 202684
Sep 22, 202676
Sep 21, 202678
Sep 20, 202672
Sep 19, 202621
Sep 18, 202624
Sep 17, 202626
Sep 16, 202633
Sep 15, 202632
Sep 14, 202630
Sep 13, 202624
Sep 12, 202625
Sep 11, 202620
Sep 10, 202616
Sep 9, 202613
Sep 8, 202617
Sep 7, 202616

Each point is npm's rolling 7-day download count.

Health Score

57/100Good

Composite score based on GitHub activity, stars, npm downloads, publish recency, dependency count, and package size.

Badge for your README

Payload Directory health badge
Markdown
[![Payload Directory](https://payloaddirectory.dev/badge/1323305566-root.svg)](https://payloaddirectory.dev/plugins/1323305566-root)
HTML
<a href="https://payloaddirectory.dev/plugins/1323305566-root"><img src="https://payloaddirectory.dev/badge/1323305566-root.svg" alt="Payload Directory"></a>
Updated Aug 5, 2026Created Aug 4, 2026Published Aug 5, 2026

README

Consent management that lives inside Payload instead of next to it.

Editors maintain third-party services, categories, descriptions and cookie declarations as ordinary Payload collections. The frontend gets a themeable banner, a settings dialog, and a script loader that keeps every non-essential tag out of the document until consent covers it.

No external platform, no per-domain licence, no second script in the critical path.

What this is not: a scanner. It does not crawl your site, discover cookies, or maintain a vendor database. What the banner claims is what you entered — keeping that accurate is your job, not the plugin's.


Install

pnpm add @bespokecode/payload-consent

Requires Payload 3.40+, React 19 and — for the server-rendered entry point — Next.js 15.

Quickstart

1. Register the plugin

// payload.config.ts
import { consentPlugin } from '@bespokecode/payload-consent'

export default buildConfig({
  plugins: [consentPlugin()],
  // …
})

On first start this creates four categories — Essential, Functional, Analytics, Marketing — which you can rename, extend or delete. Add your services under Consent → Consent services.

2. Wrap your frontend

// app/(frontend)/layout.tsx
import payloadConfig from '@payload-config'
import { ConsentProvider } from '@bespokecode/payload-consent/rsc'
import { ConsentBanner } from '@bespokecode/payload-consent/client'
import '@bespokecode/payload-consent/styles.css'

export default function Layout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="de" suppressHydrationWarning>
      <body>
        <ConsentProvider payloadConfig={payloadConfig}>
          {children}
          <ConsentBanner />
        </ConsentProvider>
      </body>
    </html>
  )
}

That is the whole integration. Scripts you add in the admin panel are now gated.

suppressHydrationWarning on <html> is not optional. The provider settles consent before the first paint by stamping attributes onto that element, so by the time React hydrates it no longer matches the server HTML — and React logs a mismatch. The attribute silences exactly that, one element deep; it does not affect your own markup. See Static rendering for what is being stamped and why.

3. Let visitors change their mind

import { openConsentSettings } from '@bespokecode/payload-consent/client'

<button onClick={openConsentSettings}>Cookie settings</button>

openConsentSettings is a plain function, not a hook — it works from anywhere, including components that are not consumers of the consent context.


How gating actually works

Nothing is injected during rendering. <ConsentProvider> ships the service definitions to the browser as data; the runtime creates <script> elements only once the relevant category is granted. A script that has never been consented to has never been in the document.

Withdrawal is deliberately asymmetric, because the browser is:

  • The cookies, localStorage and sessionStorage keys declared for that service are deleted.
  • Consent Mode signals flip back to denied.
  • If the service is set to On withdrawal → Reload the page, the page reloads.

There is no fourth step, and no plugin can offer one. Once third-party code has executed it has installed its own timers, listeners and globals; removing the <script> element undoes none of that. This is why the cookie declaration is worth maintaining — it is not just documentation for your privacy policy, it is the delete list.

When visitors are asked again

A stored decision carries the fingerprint of the configuration it was made against — computeConsentVersion over the structure: which categories exist, which are essential, and which services run under each. Change any of that and the stored decision no longer matches, so the banner returns.

Prose is deliberately excluded from the fingerprint. Fixing a typo in a category description must not re-prompt everyone; adding an analytics service to a category they accepted must.

A re-prompt is not a reset. The outdated selection is still used to pre-fill the settings dialog (previousDecisions), so a visitor who had allowed exactly one category is asked about the new shape, not asked to start over.

Enabled by default in Consent settings → Behaviour. Each category declares which signals it grants, so one toggle can map onto several.

gtag('consent','default', …denied) is emitted as an inline script in the document head, ahead of everything else. That ordering is only guaranteeable because the plugin loads Google Tag Manager itself, after consent — a CMP that does not control GTM cannot promise it.

When the decision is already known during server rendering, the matching consent update is inlined alongside the defaults, so returning visitors never pay the wait_for_update delay.

Global Privacy Control

On by default — Consent settings → Behaviour → Respect Global Privacy Control.

When a browser sends navigator.globalPrivacyControl === true and nothing is stored yet, that counts as a decision: everything non-essential is denied, and the banner does not appear. The pre-paint bootstrap honours it too, so no tag fires while React is still booting.

The derived decision is never written to the cookie. If the visitor turns the signal off later, they get a real choice instead of a rejection they never actively made. It does show up as consent in useConsent(), with id: 'global-privacy-control' — which is how you can tell the two apart if you build your own UI.

An explicit decision always wins: a stored cookie is read first, and GPC only fills the gap.

Blocking embedded content

import { ConsentGate } from '@bespokecode/payload-consent/client'

<ConsentGate scriptKey="youtube">
  <iframe src="https://www.youtube-nocookie.com/embed/…" />
</ConsentGate>

Renders a placeholder with two options until consent arrives. Load once is consent for that single instance and is deliberately not persisted — someone who wants to watch one video has not agreed to be tracked on every page from now on. Pass categorySlug instead of scriptKey to gate on a whole category. For an instant reveal on statically rendered pages, see Pre-paint embeds.

Note that hiding an iframe with CSS is not an alternative to this: a hidden iframe still loads, still reaches the provider and still sets its cookies. Consent gating has to control the DOM, not the presentation.

Your own placeholder

fallback replaces the built-in placeholder entirely. You get the two actions and the resolved service name, and render whatever you like — the gating itself is untouched:

<ConsentGate
  scriptKey="youtube"
  fallback={({ allowAlways, allowOnce, name }) => (
    <div className="video-placeholder">
      <img src="/poster.jpg" alt="" />
      <p>{name} braucht deine Zustimmung.</p>
      <button onClick={allowOnce}>Nur dieses Video laden</button>
      <button onClick={allowAlways}>{name} immer erlauben</button>
    </div>
  )}
>
  <iframe src="https://www.youtube-nocookie.com/embed/…" />
</ConsentGate>
ArgumentWhat it does
allowOnce()Reveals this one instance. Nothing is stored — a reload blocks it again.
allowAlways()Persists consent. Grants the whole category for a CMS-backed gate (scriptKey/categorySlug); grants only this gate in standalone mode.
namename prop → vendor name → service name → category name → the gate key.

The asymmetry in allowAlways is worth labelling honestly in your own UI. "Always allow YouTube" on a gate whose service sits in Marketing also switches on every other marketing service — the built-in placeholder says Always allow {service} because {service} resolves to the vendor, and that is the least misleading phrasing available at that spot. If your categories bundle several vendors, consider wording it as the category instead.

If you only want different wording, use labels rather than fallback — you keep the stylesheet and the accessibility work:

<ConsentGate
  scriptKey="youtube"
  labels={{
    allowAlways: '{service} dauerhaft erlauben',
    allowOnce: 'Einmalig laden',
    notice: 'Dieser Inhalt stammt von {service}. Beim Laden werden Daten übertragen.',
    privacyPolicy: 'Datenschutzerklärung',
  }}
>
  …
</ConsentGate>

{service} is substituted in notice and allowAlways.

Standalone gates

Sometimes there is nothing to model. A site whose analytics needs no consent, plus one booking widget you are not certain about, does not need categories and services — it needs one element held back until someone clicks.

Pass id instead of scriptKey, and the gate stands on its own:

<ConsentGate
  id="meetergo"
  name="meetergo"
  privacyPolicyUrl="https://www.meetergo.com/datenschutz"
  embed={{ src: 'https://cal.meetergo.com/…', title: 'Termin buchen', height: 700 }}
/>

This works with no <ConsentProvider>, no banner and no CMS records at all. The decision is remembered per gate in localStorage under pc-gate:<id>, not in the consent cookie — "may this one embed load" is a different question from "which categories may run", and it is not something every HTTP request needs to carry.

Add a provider later and the gate keeps working, gaining pre-paint reveal and being cleared by withdraw() along with everything else.

To revoke one from your own UI:

import {
  listStandaloneConsents,
  readStandaloneConsent,
  revokeStandaloneConsent,
} from '@bespokecode/payload-consent/client'

listStandaloneConsents()          // ['meetergo'] — everything individually allowed
readStandaloneConsent('meetergo') // true
revokeStandaloneConsent('meetergo')

Revoking notifies every mounted gate with that id immediately, so the embed disappears without a reload — localStorage fires no event in the tab that wrote it, so the plugin keeps its own subscription instead.

cookies={[…]} optionally declares what the embed stores, so revoking cleans up after it — the same list a CMS-managed service carries.

Integration scripts

Many widgets are not an iframe you place, but a container you place plus a vendor script that finds it and fills it in — meetergo, Calendly, HubSpot forms, the Maps JavaScript API all work this way. The container makes no request on its own, so only the script has to be held back:

<ConsentGate id="meetergo" name="meetergo" script={{ src: 'https://cdn.meetergo.com/…' }}>
  <div className="meetergo-iframe-block" data-link="https://cal.meetergo.com/…" />
</ConsentGate>

The script is injected after React has committed the children, so the container the vendor looks for is guaranteed to exist by the time the script runs.

Because a script that has run cannot be unloaded, revoking this kind of gate reloads the page by default — pass script={{ …, reloadOnRevoke: false }} if you know better for a given vendor. Injection goes through the same primitive the CMS script loader uses, so a script is never inserted twice regardless of which path put it there.

When to use a service record instead: if the third party belongs to the site as a whole rather than to one element — analytics, a tag manager, a pixel — put it in the CMS. That gets you pre-paint injection, the cookie declaration and a place in the settings dialog, none of which a gate can offer.

import { CookieTable } from '@bespokecode/payload-consent/client'

<CookieTable />                            // everything, grouped by category
<CookieTable categorySlug="analytics" />   // one category
<CookieTable scriptKey="ga4" />            // one service
<CookieTable scriptKey="ga4" withoutHeadings />  // no service heading

Reads the same records the banner uses, so the table in your privacy policy cannot drift away from what is actually loaded.

Separately deployed frontends

/rsc needs Next.js and Payload in the same application. If your frontend is a separate deployment, fetch the public endpoint and use the client provider directly — this path pulls in neither Payload nor next/headers:

import { ConsentClientProvider } from '@bespokecode/payload-consent/client'

const config = await fetch('https://cms.example.com/api/consent/config').then((r) => r.json())

<ConsentClientProvider config={config}>…</ConsentClientProvider>

The endpoint is public and cacheable. Cross-origin access is governed by Payload's own cors setting, not by this plugin.

There is no pre-paint bootstrap on this path, so the banner settles after hydration — see Static rendering.


Bringing your own UI

Four levels, in increasing order of how much you take on. Everything below the first keeps the gating, the storage, the Consent Mode signals and the script loader exactly as they are — only the presentation changes.

1. Restyle. CSS custom properties and data-pc-* attributes. See Styling.

2. Relabel. Banner copy comes from the CMS. The chrome around it — gate placeholder, settings dialog, cookie table — ships English defaults you override per component:

<ConsentBanner />  {/* copy from the CMS, already localised */}

<ConsentGate scriptKey="youtube" labels={{ allowOnce: 'Einmalig laden' /* … */ }} />
<CookieTable labels={{ duration: 'Speicherdauer', name: 'Name', purpose: 'Zweck' /* … */ }} />

3. Replace one piece. fallback swaps the gate placeholder (above); renderSettings swaps the whole settings dialog while keeping the built-in banner:

import { ConsentBanner, ConsentSettingsDialog } from '@bespokecode/payload-consent/client'

<ConsentBanner
  renderSettings={({ onClose }) => <MyOwnDialog onClose={onClose} />}
/>

Your dialog is rendered whenever the settings are open — from the banner's own button, from openConsentSettings(), from anywhere. onClose is the provider's closeSettings.

If you only want to relabel the built-in one, render it yourself with labels:

<ConsentBanner
  renderSettings={() => (
    <ConsentSettingsDialog
      labels={{ alwaysActive: 'Immer aktiv', provider: 'Anbieter', services: 'Dienste' }}
    />
  )}
/>

4. Replace everything. Drop <ConsentBanner> and build against the hook. This is a complete banner:

'use client'
import { useConsent } from '@bespokecode/payload-consent/client'

export const MyBanner = () => {
  const { acceptAll, config, isBannerOpen, openSettings, rejectAll } = useConsent()

  if (!isBannerOpen) return null

  return (
    <div role="dialog" aria-modal>
      <p>{config.settings.banner.description}</p>
      <button onClick={openSettings}>{config.settings.banner.labels.settings}</button>
      <button onClick={rejectAll}>{config.settings.banner.labels.rejectAll}</button>
      <button onClick={acceptAll}>{config.settings.banner.labels.acceptAll}</button>
    </div>
  )
}

Two things the built-in components do that are easy to lose here:

  • Reject and accept must carry the same visual weight. Same size, same prominence, one level deep — differing only in colour. A reject option that is smaller, greyer or hidden behind another click is the single most common reason a banner is found not to produce valid consent.
  • isBannerOpen is already the answer. It folds in the stored decision, the configuration version, Global Privacy Control and the pre-paint state. Do not re-derive it from consent.

Without the pre-paint bootstrap your own banner can flash for returning visitors during the first frame. Gate it on hydrated, or hide it with CSS on html[data-pc-decided="1"] the way the shipped stylesheet does.

useConsentOptional() is the same hook but returns null outside a provider, for components that must not hard-fail a page.


Security

The code field executes arbitrary JavaScript on every page of your site. That is what a tag manager is, not a flaw — but it means write access to consent-scripts is equivalent to full frontend access. The default lets any authenticated user manage it. Any project with more than one role should narrow that:

consentPlugin({
  access: {
    manage: ({ req }) => req.user?.roles?.includes('admin') ?? false,
  },
})

Content Security Policy. Inline scripts need unsafe-inline or a nonce. Pass yours and it is applied to the pre-paint bootstrap and to every script it or the React runtime injects:

<ConsentProvider nonce={nonce} payloadConfig={payloadConfig}>

A <ConsentGate> inside the provider inherits that nonce for its integration script. Pass nonce on the gate itself only when it stands outside a provider.

Static rendering, and why nothing flickers

<ConsentProvider> emits a small blocking inline script into the document head. It runs before the body is parsed — before the browser has painted anything — and it:

  • reads the consent cookie and stamps data-pc-decided and data-pc-granted onto <html>, which the stylesheet uses to settle the banner and the gates in the very first layout;
  • sets the Consent Mode signals, ahead of any Google tag;
  • injects the scripts consent already covers, so analytics fires without waiting for hydration.

This is the whole reason banner flicker exists in the first place: React only learns the decision in an effect, and effects run after hydration, which runs after the first paint. The cookie was never the obstacle — it has always been readable from JavaScript, and this plugin never sets HttpOnly. What matters is reading it earlier.

Everything the bootstrap does is idempotent and mirrored by the React runtime, so if it fails the page degrades to post-hydration behaviour rather than breaking. It also fails closed: an unparseable cookie grants nothing.

That first bullet is why your root layout needs suppressHydrationWarning on <html>:

<html lang="de" suppressHydrationWarning>

Stamping those attributes before hydration is the entire mechanism — but it means the element React finds differs from the one the server sent, which React reports as a hydration mismatch. The plugin sets suppressHydrationWarning on every element it owns; <html> is yours, so it has to be set there. It applies to that element's attributes alone, not to the tree beneath it, and next-themes requires it for the same reason. Without it everything still works — you just get a console warning on every page load.

Because of it, readCookieOnServer is now purely a rendering-strategy choice:

<ConsentProvider payloadConfig={payloadConfig} readCookieOnServer={false}>

true (default) reads the cookie during rendering, which opts the route into dynamic rendering. false keeps the route statically generatable. Either way the visitor sees the right thing in the first frame.

The /client entry point used standalone has no bootstrap, so there the banner still settles after hydration.

Pre-paint embeds

An ordinary <ConsentGate> with children hands its decision to React, so on a static route a consented visitor sees an empty box for a moment before the embed appears — never the wrong content, but not instant either.

For a genuinely instant reveal, let the gate render the iframe:

<ConsentGate
  scriptKey="youtube"
  embed={{ src: 'https://www.youtube-nocookie.com/embed/…', title: 'Trailer', height: 400 }}
/>

The markup then also ships inside an inert <template>, which the bootstrap clones into place before first paint. Template content does not load — no request, no cookie, nothing reaches the provider until consent exists.

The trade-off is why this needs the embed prop rather than accepting children: what the bootstrap clones is markup, not a React subtree. That is a perfect fit for a player or a map, and no fit at all for an interactive component — which is why children keep the React path.

embed and fallback compose: the iframe gets the pre-paint path, your placeholder still replaces the blocked state.

By default nothing about visitors is stored server-side. Without a login a server-side record cannot be attributed to a person anyway, and making it attributable would mean collecting an IP or a fingerprint — new personal data, collected to prove you are careful with personal data.

What the plugin gives you instead is the part that actually gets examined: all three collections and the settings global are versioned, so the configuration history shows exactly what the banner offered, and when. The visitor's own decision — timestamp, configuration version, selection — lives in their cookie and is visible to them in the settings dialog.

If a client contractually requires per-visitor records, switch them on:

consentPlugin({ logging: true })

This adds a consent-logs collection holding a random UUID, a timestamp, the configuration version and the selection. No IP, no user agent. Writes are public (visitors are anonymous); reads are restricted to access.manage.


Options

consentPlugin({
  access: {
    manage: myAdminOnlyAccess,   // who may edit services and categories
    read: myReadAccess,          // default: public
  },
  admin: { group: 'Consent' },   // false to leave collections ungrouped
  categories: { slug: 'consent-categories', overrides: {} },
  scripts: { slug: 'consent-scripts', overrides: {} },
  settings: { slug: 'consent-settings', overrides: {} },
  cookie: { name: 'pc_consent', maxAgeDays: 182, domain: '.example.com' },
  endpoints: { config: '/consent/config', log: '/consent/log' },  // false to disable
  logging: false,
  seed: true,
  disabled: false,
  onConfigChange: async ({ req }) => { revalidateTag('consent') },
})

disabled: true keeps the collections and global registered — so switching the plugin off does not change your database schema — while removing endpoints, seeding and hooks.

cookie supplies the default values for the corresponding fields in the settings global. The global is the runtime source of truth, so an editor can still change them.

onConfigChange fires whenever a category or service is created, changed or deleted, and whenever the settings global is saved — not for consent logs, which change nothing about what the banner offers. <ConsentProvider> reads through the Local API on every request, so a plain setup needs nothing here; it matters once you cache that read, either with unstable_cache around buildConsentConfig or by serving /api/consent/config from a CDN.

Exports

Entry pointContents
@bespokecode/payload-consentconsentPlugin, buildConsentConfig, computeConsentVersion, sanitizeConsentConfig, DEFAULT_* constants, types
…/rscConsentProvider, buildConsentConfig, getConsentPluginConfig
…/clientcomponents, hooks and storage helpers — see below
…/typestypes only
…/styles.cssbase stylesheet

…/client in full:

ComponentsConsentBanner, ConsentSettingsDialog, ConsentGate, CookieTable, ConsentClientProvider
HooksuseConsent, useConsentOptional
ImperativeopenConsentSettings
Standalone gatesreadStandaloneConsent, grantStandaloneConsent, revokeStandaloneConsent, listStandaloneConsents, clearStandaloneConsents
StoragereadStoredConsent, parseStoredConsent, clearDeclaredStorage
TypesConsentGateProps, ConsentGateEmbed, ConsentGateLabels, ConsentBannerProps, ConsentSettingsDialogProps, ConsentSettingsDialogLabels, CookieTableProps, CookieTableLabels, ConsentClientProviderProps, ConsentContextValue

useConsent()

const {
  config,               // the whole public configuration, incl. banner copy
  categories,           // shortcut for config.categories
  scripts,              // shortcut for config.scripts
  consent,              // the decision in effect, or null
  previousDecisions,    // the last selection, even if made against an older config
  hydrated,             // false until the stored decision has been read
  nonce,                // the CSP nonce the provider was given

  isCategoryGranted,    // (slug) => boolean
  isScriptGranted,      // (key) => boolean

  acceptAll, rejectAll,
  save,                 // (decisions: Record<string, boolean>, method?) => void
  withdraw,             // revoke everything, incl. standalone gates, and re-show the banner

  isBannerOpen, isSettingsOpen, openSettings, closeSettings,
} = useConsent()

save() forces essential categories on regardless of what you pass, so a partial selection object is safe.

<ConsentProvider> props

PropDefault
payloadConfig—required: import payloadConfig from '@payload-config'
localeconfig defaultwhich locale the banner copy is read in
nonce—CSP nonce for the bootstrap and every injected script
readCookieOnServertruefalse keeps the route statically generatable
consentConfig—skip the database and use this configuration, e.g. one you wrapped in your own cache

<ConsentGate> props

Exactly one of scriptKey, categorySlug or id identifies the gate. With none of them the gate renders its content ungated and warns in development — blocking forever would hide content with no way for the visitor to unblock it.

Prop
scriptKeygate on one CMS service, by its identifier
categorySluggate on a whole CMS category
idstandalone mode — no CMS record, no provider required
childrenwhat to reveal, via React
embedreveal this iframe instead of children, with pre-paint
scriptload a vendor script once children are in the DOM (integration scripts)
fallbackyour own placeholder
labelsoverride the built-in placeholder's wording
namedisplay name; required in standalone mode, overrides the CMS name otherwise
privacyPolicyUrlshown in the placeholder; falls back to the vendor's URL from the CMS
cookieswhat the embed stores, deleted on revocation — standalone mode only
nonceCSP nonce for the integration script; inherited from the provider when there is one

embed takes src and title plus optional allow, allowFullScreen, className, height, width, loading, referrerPolicy, sandbox.

script takes src plus optional strategy ('async' default, 'defer', 'sync'), placement ('bodyEnd' default, 'head'), attributes and reloadOnRevoke (default true).

A scriptKey that matches no service — a typo, or a service an editor deleted — blocks the gate and warns in development. Failing open there would load third-party content nobody consented to, and the misconfiguration would be invisible precisely because everything appeared to work. Note that a service whose category was deleted is dropped from the configuration server-side, so it reaches the frontend as exactly this case.

Since there is then no category to grant, such a gate offers only Load once — the built-in placeholder hides the "always allow" button rather than showing one that cannot persist anything. A fallback still receives allowAlways; it is a no-op in this state.

Styling

Everything is driven by CSS custom properties, and every element carries a data-pc-* attribute. Override the properties for a reskin, or target the data attributes to restyle from scratch without fighting specificity.

:root {
  /* layout */
  --pc-font: inherit;
  --pc-radius: 0.5rem;
  --pc-radius-sm: 0.3rem;
  --pc-gap: 1rem;
  --pc-max-width: 46rem;
  --pc-z: 2147483000;

  /* surfaces */
  --pc-color-surface: #ffffff;
  --pc-color-fg: #14161a;
  --pc-color-muted: #5b6270;
  --pc-color-border: #dfe3e9;
  --pc-color-subtle: #f5f6f8;

  /* buttons */
  --pc-color-accent: #14161a;
  --pc-color-accent-fg: #ffffff;
  --pc-color-neutral: #eceef2;
  --pc-color-neutral-fg: #14161a;

  /* the rest */
  --pc-color-overlay: rgb(10 12 16 / 55%);
  --pc-shadow: 0 1px 2px rgb(10 12 16 / 6%), 0 12px 32px rgb(10 12 16 / 14%);
  --pc-focus: 0 0 0 2px var(--pc-color-surface), 0 0 0 4px var(--pc-color-accent);
}

Light and dark are both handled via prefers-color-scheme; every colour above is redeclared in the dark block, so overriding only the light values leaves dark mode on the defaults.

Hooks for your own CSS

On <html>
data-pc-decided"1" once a decision exists, "0" while none does — set before first paint
data-pc-grantedspace-separated slugs of every granted category

Both are written by the pre-paint bootstrap and kept in step by the React runtime, which is what lets CSS settle the banner in the first frame:

html[data-pc-decided='1'] .my-banner { display: none; }
On elements
data-pc-banner, data-pc-dialog, data-pc-overlaythe banner, the settings dialog, the backdrop
data-pc-cookies, data-pc-category, data-pc-scriptthe cookie table and its groups
data-pc-actionaccept-all, reject-all, save, settings, close, toggle-details, allow-once, allow-always
data-pc-gatethe gate host, valued with its category or standalone id
data-pc-gate-modestandalone on gates that carry an id
data-pc-hydrated, data-pc-revealedset by the runtime and the bootstrap; the stylesheet uses them to hand a pre-painted embed over to React without a flash

Note that Accept all and Reject all share every dimension that carries visual weight and differ only in colour. Making the reject option smaller, greyer or one level deeper is the most common reason a banner is found not to produce valid consent — please keep them equal.

Localisation

Two separate layers, and the difference matters:

CMS content is localised. Category names, service descriptions, cookie purposes and all banner copy — including the button labels — are localized fields. <ConsentProvider locale> picks which one is rendered. If your project has no localization config they behave as ordinary fields, so the plugin works unchanged in single-language projects.

Component chrome is not. The gate placeholder, the settings dialog's structural labels and the cookie table's column headings ship English defaults in code, because they are not editorial copy. Override them with the labels prop on each component — see Bringing your own UI.

Admin field labels ship in English and German.


Development

pnpm install
cp dev/.env.example dev/.env
pnpm dev              # Payload admin + a demo frontend on :3000
pnpm test:int         # Vitest against an in-memory MongoDB
pnpm test:e2e         # Playwright against the dev app
pnpm build

The dev app under dev/ imports the plugin straight from src/.


Created by

Built and maintained by Max Eckel at BespokeCode — a software studio in Munich building websites and custom software, automating business processes, and advising mid-sized companies on digitalisation.

Bugs and feature requests belong in the issue tracker. For commercial support, a consent setup review, or custom Payload work, get in touch.

Licence

MIT

Similar plugins