Skip to content

Build your own UI

When you want a custom look or per-app rules (categories, scripts, cookies, signal mapping), use @vscookies/core directly. The React provider is a thin wrapper over the same store.

import { createCMP, DEFAULT_CATEGORY_RULES } from "@vscookies/core";
export const cmp = createCMP({
categories: {
...DEFAULT_CATEGORY_RULES, // suggested defaults; spread to keep their labels
heatmaps: {
title: "Heatmaps",
description: "Helps us see which areas of the page get attention.",
icon: "/icons/heatmap.svg",
image: "/images/heatmaps-preview.png",
default: false,
scripts: [{ src: "/vendor/heatmaps.js", execution: "async" }],
cookies: [{ name: "heatmap_id", options: { maxAge: 2592000 }, server: true }],
signals: { analytics_storage: true },
},
},
serverEndpoint: "/api/consent-cookies",
});

createCMP() activates itself in the browser; there is no init() call. On the server it is a no-op, so importing it during SSR is safe. The four built-in categories are suggestions, not a closed set: any string key works.

const off = cmp.on("consentUpdated", (record) => {
if (record.categories.heatmaps) initHeatmaps();
});
cmp.getConsentState(); // { necessary: true, ..., heatmaps: false }
cmp.updateConsent({ heatmaps: true }); // persist + signal + inject/purge
cmp.updateConsent({}, { cookies: { heatmap_id: false } }); // deny one cookie
cmp.updateConsent({}, { scripts: { "/vendor/heatmaps.js": false } }); // halt one script
off();

updateConsent performs a partial update; omitted categories keep their value. The optional second argument, { cookies?, scripts? }, denies individual managed items (cookies by name, scripts by src) — an override may only deny an item within an allowed category; switching the category off switches off all its items. Overrides are stored as record.cookies / record.scripts. No reload is required, so this works in SPAs.

CMP owns all third-party tag injection. Remove non-essential <script> tags from your HTML and declare them in categories instead. That is what lets CMP write the denied defaults into window.dataLayer before any tag can execute.

analytics: {
scripts: [
{ src: "/vendor/gtm.js", execution: "defer" }, // dependent: in order
{ src: "/vendor/ads.js", execution: "defer" },
],
}

async is for isolated tags, defer (the default) for sequentially dependent ones. Tags are never inserted synchronously and document.write() is never used. On revocation, pending tags are removed and further execution is halted.

The four flags — analytics_storage, ad_storage, ad_user_data, ad_personalization — are pushed as denied at startup. Each category declares which signals it grants via signals; CMP pushes ["consent", "update", …] to window.dataLayer whenever state changes:

window.dataLayer.push(["consent", "update", {
analytics_storage: "granted",
ad_storage: "denied",
ad_user_data: "denied",
ad_personalization: "denied",
}]);

Custom signal keys are allowed too — declare them on a category and they are included as denied in the startup payload.

Each category’s cookies are written while allowed and purged on revocation.

  • cookieStore.set() / delete() are used where available, with a document.cookie fallback; change events replace polling.
  • Domain is omitted by default (host-only scope). __Host- names force Secure, Path=/ and no Domain. SameSite=None requires Secure; add partitioned: true for CHIPS in embedded contexts.
  • Cookies with maxAge over seven days, or server: true, are sent to serverEndpoint instead of being written client-side (Safari ITP).

See Core › Cookie governance for the server helpers used to emit those headers.

import { CookieConsentProvider, useCookieConsent } from "@vscookies/react";
function Banner() {
const { hasConsented, acceptAll, rejectAll, catalog } = useCookieConsent();
if (hasConsented) return null;
return (
<div>
{catalog.filter((c) => !c.essential).map((c) => (
<p key={c.name}>{c.icon && <img src={c.icon} alt="" />}{c.title ?? c.name}</p>
))}
<button onClick={rejectAll}>Reject all</button>
<button onClick={acceptAll}>Accept all</button>
</div>
);
}

catalog is the resolved config, including each category’s title, description, icon and image, plus its cookies metadata — ready for a future preference panel.

For a “Cookie settings” link, use the UI-only signal instead of reset() so the current decision stays in place until the user saves a new one:

import { useCookieConsent, usePreferencesOpen, setPreferencesOpen } from "@vscookies/react";
const { manageCookies } = useCookieConsent(); // <button onClick={manageCookies}>
const open = usePreferencesOpen(); // shared open-state, SSR-safe
// close with setPreferencesOpen(false)

manageCookies() emits an event; it does not change consent, clear the record or touch tags. Vanilla exports the same manageCookies() plus setPreferencesOpen / isPreferencesOpen / onPreferencesChange from @vscookies/vanilla.

import { parseConsentCookie, buildSetCookieHeader } from "@vscookies/core/server";
const record = parseConsentCookie(request.headers.get("cookie") ?? "");
const header = buildSetCookieHeader("heatmap_id", value, {
maxAge: 2592000,
sameSite: "lax",
});

These helpers throw if called in a browser, so SSR code cannot accidentally run client-side. Client rendering always starts from the same denied snapshot; the stored decision is read after hydration, which prevents mismatches.

createCMP({ debug: true, dryRun: true });

debug defaults to NODE_ENV !== "production". dryRun logs every intended action without injecting tags or writing cookies.