Core
@vscookies/core is the UI-agnostic engine behind every other package. It has
no dependencies and is safe to import in SSR/Node (cookie access no-ops when
document is undefined). Both the React and vanilla runtimes bundle it, so you
only need this zip when driving the store directly for a fully custom UI.
Download vscookies-core-v0.2.0.zip from the
VS GOODS store and unzip it into
vendor/vscookies/core/; see Installing from the zip.
import { ConsentStore, CookieManager } from "@vscookies/core";ConsentStore
Section titled “ConsentStore”A ConsentStore reads and writes a single JSON record in a cookie, and exposes
per-category helpers.
Constructor
Section titled “Constructor”const store = new ConsentStore(options?: ConsentStoreOptions);| Option | Type | Default | Description |
|---|---|---|---|
storageKey | string | "vsc_consent" | Cookie name that stores the record. |
version | number | 1 | Consent version. A record with a different version is ignored. |
categories | ConsentCategory[] | ["necessary","preferences","analytics","marketing"] | Categories tracked for this site. |
defaults | Partial<ConsentState> | { necessary: true } | Initial values before any decision. |
essential | ConsentCategory[] | ["necessary"] | Categories that are always granted. |
cookie | CookieManagerOptions | {} | Per-instance cookie options (see below). |
Methods
Section titled “Methods”| Method | Returns | Description |
|---|---|---|
getRecord() | ConsentRecord | null | The full stored record, or null if absent/expired. |
get() | ConsentState | Effective per-category booleans (defaults when unset). |
hasConsented() | boolean | true when a record exists for the current version. |
isAllowed(category) | boolean | true for "necessary" always; otherwise the stored value. |
acceptAll() | ConsentRecord | Accept every category, decision "accepted". |
rejectAll() | ConsentRecord | Reject every optional category, decision "rejected". |
set(patch, overrides?) | ConsentRecord | Patch categories and/or per-item overrides ({ cookies?, scripts? }), decision "custom". Overrides merge with previously stored ones. |
reset() | void | Delete the record so the banner reappears. |
refresh() | void | Drop the read cache after an external cookie change. |
subscribe(listener) | () => void | Observe writes/reset; returns an unsubscribe function. |
const store = new ConsentStore();
store.hasConsented(); // false on first visitif (store.isAllowed("analytics")) { loadAnalytics();}
store.acceptAll();store.set({ analytics: false }); // partial category updatestore.set({}, { cookies: { heatmap_id: false } }); // deny one cookiestore.set({}, { scripts: { "/vendor/x.js": false } }); // halt one scriptstore.reset();CMP SDK
Section titled “CMP SDK”createCMP(config) turns a declarative config into a small SDK that owns tag
injection, consent signals and category cookie lifecycle. It activates itself in
the browser (SSR-safe no-op on the server).
import { createCMP, DEFAULT_CATEGORY_RULES } from "@vscookies/core";
export const cmp = createCMP({ categories: { ...DEFAULT_CATEGORY_RULES, heatmaps: { title: "Heatmaps", description: "Where visitors focus on the page.", icon: "/icons/heatmap.svg", image: "/images/heatmaps.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", debug: process.env.NODE_ENV !== "production", dryRun: false,});Methods
Section titled “Methods”| Method | Returns | Description |
|---|---|---|
on("consentUpdated", cb) | () => void | Subscribe; callback receives the full new ConsentRecord (decision, categories, cookie overrides). |
getConsentState() | ConsentState | Current effective per-category booleans. |
updateConsent(patch, overrides?) | void | Patch categories and/or per-item overrides ({ cookies?, scripts? }); persist, signal and sync tags/cookies. |
That is the whole public SDK. UI state lives in useCookieConsent(); SSR helpers
live in @vscookies/core/server.
Per-item overrides (cookies & scripts)
Section titled “Per-item overrides (cookies & scripts)”Categories are the unit of consent; individual managed items — cookies (by
name) and scripts (by src) — can be denied for finer-grained preference UIs.
Overrides are stored on the record as cookies? / scripts?
(Record<name, boolean>, names must be unique across categories) and only
exist for "custom" decisions — acceptAll() / rejectAll() clear them.
Resolution rule, implemented once and shared by both kinds:
essential category is always on → otherwise the category value decides → a per-item override may only turn the item OFF within an allowed category.
In one sentence: switching a category off switches off all its items.
Three pure helpers exported from @vscookies/core (and re-exported by both
runtimes) implement and expose this rule:
import { isCookieAllowed, isScriptAllowed, countActiveItems } from "@vscookies/core";
const overrides = { cookies: record?.cookies, scripts: record?.scripts };isCookieAllowed(catalog, "marketing", "ad_id", state, overrides);isScriptAllowed(catalog, "analytics", "https://…/gtm.js", state, overrides);countActiveItems(catalog, state, overrides); // "N items active"catalog is the resolved rules array (from useCookieConsent() in React, or
the CMP internals). countActiveItems always counts items of essential
categories.
What a script sets (setsCookies)
Section titled “What a script sets (setsCookies)”Third-party scripts often plant cookies on the user’s browser. Declare them on the script rule so the CMP can purge them when the script is denied, and so preference UIs can show what it sets:
scripts: [ { src: "https://www.googletagmanager.com/gtm.js?id=GTM-XXXX", title: "Google Tag Manager", description: "Analytics and ads.", setsCookies: ["_ga", "_ga_XXXXXX", "_gid"], },],When the script is denied (category revoked or per-script override), the CMP
removes the element and purges every name in setsCookies. Client-side purge
(document.cookie removal) works for JS-writable cookies with matching
path/domain — if the same name is also declared as a category cookies
entry, its options are used for removal so attributes always match the write.
HttpOnly and cross-site cookies cannot be deleted from JS — for those,
configure serverEndpoint: on revocation the CMP also POSTs
{ name, action: "purge", options } there, and your server answers with a
Set-Cookie that expires the name (Max-Age=0, same path/domain).
Category rules
Section titled “Category rules”| Field | Type | Description |
|---|---|---|
default | boolean | Initial value before any decision (default false). |
essential | boolean | Always granted and not revocable (necessary uses this). |
scripts | { src, execution?, attrs?, title?, description?, icon?, image?, setsCookies? }[] | Tags injected only while allowed. execution is async or defer (default). setsCookies declares cookie names the script sets, purged on deny (see above). |
cookies | { name, value?, options?, server?, title?, description?, icon?, image?, accent? }[] | Cookies written while allowed, purged on revocation; individually overridable by name (see above). title/description/icon/image/accent are display metadata shown in preference UIs. |
signals | Partial<Record<ConsentSignalKey, boolean>> | Signals granted by this category. |
title, description, icon, image, accent | string | Presentation metadata for preference UIs (accent colors category tabs). |
The four built-ins are suggestions: spread DEFAULT_CATEGORY_RULES to keep their
labels, and add any string-keyed categories you need. Stored decisions always
win over default values.
createCMP() pushes all four Google Consent Mode flags as denied first, then a
["consent", "update", …] payload to window.dataLayer whenever allowed
signals change. Because CMP is the only tag injector, defaults are in place
before any tag runs — remove non-essential tags from your HTML.
The runtime’s useCookieConsent() exposes a read-only catalog array with the
resolved rules (including metadata) for building preference panels.
CookieManager
Section titled “CookieManager”CookieManager is the low-level cookie reader/writer used by ConsentStore.
Use it directly if you need raw cookie access.
const cookies = new CookieManager({ prefix: "app_" });cookies.set("theme", "dark", { maxAge: 60 * 60 });cookies.get("theme"); // "dark"cookies.has("theme"); // truecookies.getAll(); // { theme: "dark", ... } (prefix stripped)cookies.remove("theme");CookieManagerOptions
Section titled “CookieManagerOptions”Extends CookieOptions with prefix.
| Option | Type | Default | Description |
|---|---|---|---|
prefix | string | — | Prepended to every cookie name; stripped by getAll(). |
path | string | "/" | Cookie Path. |
domain | string | — | Cookie Domain. Omitted by default (host-only). |
expires | Date | number | — | Date or days-from-now. |
maxAge | number | — | Max-Age in seconds. |
secure | boolean | true on HTTPS | Adds Secure. |
sameSite | "strict" | "lax" | "none" | "lax" | SameSite attribute. none requires secure. |
partitioned | boolean | false | CHIPS: requires secure; pair with sameSite: "none" in third-party contexts. |
encode / decode | (v: string) => string | URI codec | Custom value codec. |
Writes prefer the asynchronous cookieStore.set() / delete() API where
available and fall back to document.cookie elsewhere. onChange(listener)
subscribes to the CookieStore change event instead of polling
document.cookie. Reads stay synchronous via document.cookie.
Cookie governance
Section titled “Cookie governance”Attributes are normalized for every write (client and server):
- No
Domainattribute unless explicitly supplied. __Host-<name>cookies require HTTPS, forcePath=/,Secure, and drop anyDomainattribute.SameSite=NonerequiresSecure;Partitionedalso requiresSecure. Invalid combinations are warned about in non-production builds.- Cookies older than seven days (or flagged
server: true) should be set with a serverSet-Cookieheader to survive Safari ITP truncation.
Two pure helpers are available from @vscookies/core/server. They throw if
called in a browser, so SSR code can never be mismatched into client execution:
import { parseConsentCookie, buildSetCookieHeader } from "@vscookies/core/server";
const record = parseConsentCookie(request.headers.get("cookie") ?? "");const header = buildSetCookieHeader("analytics_id", value, { maxAge: 2592000, sameSite: "lax",});Write multiple cookies per category
Section titled “Write multiple cookies per category”Most sites need more than one cookie per category. Keep a typed registry and sync it from the consent state: allowed categories are written, denied categories are removed, and unchanged categories are left alone.
import { ConsentStore, CookieManager, type ConsentCategory, type ConsentState, type CookieOptions,} from "@vscookies/core";
type ManagedCookie = { name: string; value: string | (() => string); /** Attributes for writing. `maxAge` is fine here. */ set?: CookieOptions; /** Attributes for deleting: same path/domain, no maxAge/expires. */ clear?: CookieOptions;};
const SHARED = { path: "/", sameSite: "lax" } as const;
const COOKIES: Record<ConsentCategory, ManagedCookie[]> = { necessary: [ { name: "session", value: () => crypto.randomUUID(), set: { ...SHARED, maxAge: 1800 }, clear: SHARED, }, ], preferences: [ { name: "lang", value: () => navigator.language, set: { ...SHARED, maxAge: 31536000 }, clear: SHARED }, { name: "layout", value: "compact", set: { ...SHARED, maxAge: 31536000 }, clear: SHARED }, ], analytics: [ { name: "analytics_id", value: () => crypto.randomUUID(), set: { ...SHARED, maxAge: 31536000 }, clear: SHARED }, { name: "analytics_bucket", value: "b", set: { ...SHARED, maxAge: 86400 }, clear: SHARED }, ], marketing: [ { name: "campaign", value: () => new URLSearchParams(location.search).get("utm_campaign") ?? "", set: { ...SHARED, maxAge: 604800 }, clear: SHARED, }, { name: "ad_id", value: () => crypto.randomUUID(), set: { ...SHARED, maxAge: 7776000 }, clear: SHARED }, ],};
export const consent = new ConsentStore({ version: 2, categories: ["necessary", "preferences", "analytics", "marketing"],});const cookies = new CookieManager({ prefix: "acme_" });
function applyCategory(category: ConsentCategory, allowed: boolean) { for (const cookie of COOKIES[category]) { if (allowed) { const value = typeof cookie.value === "function" ? cookie.value() : cookie.value; cookies.set(cookie.name, value, cookie.set); } else { cookies.remove(cookie.name, cookie.clear ?? SHARED); } }}
let previous: ConsentState | null = null;
export function syncCategoryCookies(state = consent.get()) { for (const category of Object.keys(COOKIES) as ConsentCategory[]) { if (previous === null || state[category] !== previous[category]) { applyCategory(category, state[category]); } } previous = state;}
consent.subscribe(syncCategoryCookies);syncCategoryCookies(); // after hydration: writes allowed groups, removes denied onesnecessary is always true, so its cookies are written on the first sync and
never removed. Only changed categories are rewritten, so an analytics_id is not
regenerated when the user changes a marketing preference. To refresh values while
a category stays allowed, call applyCategory(category, true) directly.
| Type | Definition |
|---|---|
DefaultConsentCategory | "necessary" | "preferences" | "analytics" | "marketing" |
ConsentCategory | DefaultConsentCategory | (string & {}) — defaults are suggested, custom names allowed |
ConsentState<C> | Record<C, boolean> |
ConsentCookieState | Record<string, boolean> — per-item overrides keyed by cookie name or script src |
ConsentOverrides | { cookies?: ConsentCookieState; scripts?: ConsentCookieState } — second arg of set / updateConsent |
ConsentDecision | "unset" | "accepted" | "rejected" | "custom" |
ConsentRecord<C> | { version: number; decision: ConsentDecision; categories: ConsentState<C>; cookies?: ConsentCookieState; scripts?: ConsentCookieState; updatedAt: string } |
ConsentStoreOptions<C> | Constructor options above, plus defaults and essential |
CookieOptions | Options in the cookie table above |
CookieManagerOptions | CookieOptions & { prefix?: string } |
DisplayMeta | { title?, description?, icon?, image?, accent? } |
ScriptRule | DisplayMeta & { src, execution?: "async" | "defer", attrs?, setsCookies? } |
ManagedCookie | DisplayMeta & { name, value?, options?, server? } |
CategoryRule<C> | DisplayMeta & { default?, essential?, scripts?, cookies?, signals? } |
CMPConfig<C> | { categories?, store?, serverEndpoint?, debug?, dryRun? } |
CMP<C> | { on, getConsentState, updateConsent } |
ConsentCatalog<C> | Read-only array of CategoryRule<C> & { name: C } |
ConsentSignalKey | The four Google Consent Mode keys, plus any custom string |
SameSite | "strict" | "lax" | "none" |
Stored record
Section titled “Stored record”ConsentStore persists a single JSON cookie. With defaults it is written as
vsc_consent with Max-Age=31536000 (365 days), SameSite=Lax, and Path=/:
{ "version": 1, "decision": "custom", "categories": { "necessary": true, "preferences": true, "analytics": false, "marketing": false }, "cookies": { "heatmap_id": false }, "scripts": { "/vendor/heatmaps.js": false }, "updatedAt": "2026-01-01T00:00:00.000Z"}cookies / scripts are optional and omitted for "accepted" / "rejected"
decisions (those clear all overrides); older records without them remain valid
(the fields are additive, no version bump needed).
Bumping version invalidates every prior record (a re-consent prompt). Bump it
whenever your cookie policy changes.