@zunoy/consent
v0.1.0
Published
Zunoy Privacy & Consent SDK — Prebuilt, Headless and Server modes for consent banners, vendor script gating, and GDPR/CCPA consent logging against a Zunoy CMS workspace.
Maintainers
Readme
@zunoy/consent
Privacy & Consent SDK for websites built on Zunoy CMS — cookie banner state, GDPR/CCPA-aware geo templates, vendor script gating, and consent logging, without hand-rolling any of it.
The Zunoy CMS backend never injects scripts or renders a banner itself — it publishes a config; this SDK is what reads that config on your site and acts on it. See Zunoy CMS for the admin side (Banner builder, categories, vendor catalog, consent log/audit trail).
Install
npm install @zunoy/consentreact is an optional peer dependency — only needed if you use the /react
entry point (Headless mode). The core package (@zunoy/consent) has zero
dependencies and runs anywhere JavaScript does: browser, Node SSR, Edge,
Cloudflare Workers.
Quick start (Headless — React)
import { ConsentProvider, useConsent } from '@zunoy/consent/react';
function App({ children }) {
return (
<ConsentProvider options={{ baseUrl: 'https://your-cms.example.com/api/v1/cms', apiKey: 'YOUR_API_KEY' }}>
{children}
<CookieBanner />
</ConsentProvider>
);
}
function CookieBanner() {
const { needsConsent, config, acceptAll, rejectAll } = useConsent();
if (!needsConsent || !config) return null;
return (
<div>
<p>{config.banner.content.en?.body}</p>
<button onClick={rejectAll}>Reject all</button>
<button onClick={acceptAll}>Accept all</button>
</div>
);
}That's the entire integration. The provider:
- fetches your workspace's published config
- resolves the visitor's region against your geo rules (EU/UK → opt-in, US → opt-out + persistent "Do Not Sell" link, etc.)
- persists the visitor's decision (first-party
localStorage+ a cookie mirror for subdomain sharing) - injects/removes each configured vendor's
<script>tag as its category is granted or revoked - fires the consent event back to your workspace's audit log — fire-and-forget, never blocks your page
You bring the markup; the SDK never renders anything for you in this mode — that's the point of "Headless."
Where to get baseUrl and apiKey
Both come from your Zunoy CMS workspace: Privacy & Consent → Install in the
admin shows a copy-paste snippet pre-filled with your workspace's values. The
apiKey is the same public X-Zunoy-Key your site already uses for content —
it identifies the workspace, it isn't a secret that needs server-side hiding.
Three modes
| Mode | Import | Status | Use when |
|---|---|---|---|
| Headless | @zunoy/consent/react | ✅ Available | You want to build your own banner UI with your own design system — the common case for a Next.js/React site. See Quick Start above. |
| Prebuilt | — | 🚧 Planned | Zero-config, pre-styled <ConsentBanner /> matching your Banner Builder config exactly — for sites that don't want to write any banner markup at all. |
| Server | — | 🚧 Planned | SSR/Edge/Workers-side config resolution so the very first paint already reflects the right region/consent state — no client-side banner flash. |
The core ConsentManager class (below) already works standalone in all of
those contexts today; the Prebuilt and Server conveniences (a ready-made
component, framework-specific helpers) are what's still in progress.
Core API (framework-agnostic)
If you're not using React, or want lower-level control, use the core class
directly — this is also literally what the /react entry point is built on
top of.
import { ConsentManager } from '@zunoy/consent';
const manager = new ConsentManager({
baseUrl: 'https://your-cms.example.com/api/v1/cms',
apiKey: 'YOUR_API_KEY',
region: { explicit: 'EU' }, // optional — omit to rely on regionSource.strategy (edge header, etc.)
});
await manager.load(); // fetch + cache the published config
manager.needsConsent(); // boolean — should you show a banner right now?
manager.getTemplate(); // the matched geo rule ({ template, showBanner, persistentLink })
manager.getRegion(); // resolved region string, e.g. "EU"
manager.currentConsent(); // stored ConsentState | null
manager.enabledVendors(); // vendors whose category is currently granted
manager.acceptAll();
manager.rejectAll();
manager.acceptAnalytics(); // grants only "analytics", preserves the rest
manager.acceptMarketing(); // grants only "marketing", preserves the rest
manager.setCategory('functional', true);
manager.withdrawConsent(); // revokes everything except required categories
manager.dismiss(); // banner closed without an explicit choice — logged, no state change
const unsubscribe = manager.onConsentChanged(state => {
// re-render your UI, sync analytics tools, etc.
});Manual vendor script control
The React provider does this for you automatically. If you're not using React:
import { syncVendorScripts } from '@zunoy/consent';
manager.onConsentChanged(() => {
syncVendorScripts(manager.enabledVendors());
});Google Consent Mode v2
If your workspace has Google Consent Mode enabled on a GA4 or Google Ads vendor (Privacy & Consent → Scripts & Vendors in the admin), the SDK handles both required signals automatically — nothing to call yourself:
- Default —
gtag('consent', 'default', {...})fires the momentConsentManager.load()resolves, defaulting every Google consent type todenied(or the visitor's already-stored decision, if any). - Update —
gtag('consent', 'update', {...})fires synchronously inside every consent action (acceptAll,setCategory,withdrawConsent, ...), before the corresponding vendor<script>is injected.
This satisfies Google's requirement (mandatory for EEA traffic using Google
Ads/GA4 remarketing since March 2024) that consent signals reach dataLayer
before gtag.js finishes loading — dataLayer.push() queues safely even
before gtag.js exists, which is exactly what both pushes rely on.
For the strictest possible timing, Google's own guidance is to set the
default state inline in your page's <head>, before any other script —
including this SDK's own JS bundle. Add this once, as early as possible:
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){ dataLayer.push(arguments); }
gtag('consent', 'default', {
'ad_storage': 'denied', 'ad_user_data': 'denied', 'ad_personalization': 'denied',
'analytics_storage': 'denied', 'functionality_storage': 'denied', 'personalization_storage': 'denied',
});
</script>The SDK's own default push (step 1 above) is a safety net for sites that skip
this — both are safe to run together; gtag.js only ever reads the latest
state once it loads.
Fallback: skip the SDK, call the REST API directly
The SDK is a convenience layer, not a requirement — every Zunoy CMS workspace exposes two plain REST endpoints your own code (any language, any framework, a mobile app) can call directly:
GET https://your-cms.example.com/api/v1/cms/v1/privacy/config
Header: X-Zunoy-Key: <your-api-key>
# → the published config (banner, categories, vendors, geoRules, consentPolicy, ...)
# ETag = policyVersion; Cache-Control: public, max-age=300POST https://your-cms.example.com/api/v1/cms/v1/privacy/consent
Header: X-Zunoy-Key: <your-api-key>
Content-Type: application/json
{
"logId": "<a uuid you generate>",
"timestamp": "2026-07-18T14:19:07Z",
"policyVersion": "2026.07.18",
"clientStableId": "<a stable first-party id you generate/persist>",
"region": "EU",
"action": "explicit_grant",
"consentedCategories": ["necessary", "analytics"],
"rejectedCategories": ["marketing"]
}
# → always 202 Accepted — a logging hiccup must never break your page.Valid action values: explicit_grant, reject_all, withdraw, update,
dismiss. Full endpoint documentation (including the admin config/publish API)
is in your CMS's own Resources → Docs → Privacy & Consent page.
TypeScript
Fully typed — PublishedConfig, ConsentState, Vendor, Category,
GeoRule, ConsentAction and friends are all exported from the package root.
License
MIT © Zunoy
