Skip to content

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";

A ConsentStore reads and writes a single JSON record in a cookie, and exposes per-category helpers.

const store = new ConsentStore(options?: ConsentStoreOptions);
OptionTypeDefaultDescription
storageKeystring"vsc_consent"Cookie name that stores the record.
versionnumber1Consent version. A record with a different version is ignored.
categoriesConsentCategory[]["necessary","preferences","analytics","marketing"]Categories tracked for this site.
defaultsPartial<ConsentState>{ necessary: true }Initial values before any decision.
essentialConsentCategory[]["necessary"]Categories that are always granted.
cookieCookieManagerOptions{}Per-instance cookie options (see below).
MethodReturnsDescription
getRecord()ConsentRecord | nullThe full stored record, or null if absent/expired.
get()ConsentStateEffective per-category booleans (defaults when unset).
hasConsented()booleantrue when a record exists for the current version.
isAllowed(category)booleantrue for "necessary" always; otherwise the stored value.
acceptAll()ConsentRecordAccept every category, decision "accepted".
rejectAll()ConsentRecordReject every optional category, decision "rejected".
set(patch, overrides?)ConsentRecordPatch categories and/or per-item overrides ({ cookies?, scripts? }), decision "custom". Overrides merge with previously stored ones.
reset()voidDelete the record so the banner reappears.
refresh()voidDrop the read cache after an external cookie change.
subscribe(listener)() => voidObserve writes/reset; returns an unsubscribe function.
const store = new ConsentStore();
store.hasConsented(); // false on first visit
if (store.isAllowed("analytics")) {
loadAnalytics();
}
store.acceptAll();
store.set({ analytics: false }); // partial category update
store.set({}, { cookies: { heatmap_id: false } }); // deny one cookie
store.set({}, { scripts: { "/vendor/x.js": false } }); // halt one script
store.reset();

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,
});
MethodReturnsDescription
on("consentUpdated", cb)() => voidSubscribe; callback receives the full new ConsentRecord (decision, categories, cookie overrides).
getConsentState()ConsentStateCurrent effective per-category booleans.
updateConsent(patch, overrides?)voidPatch 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.

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.

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

FieldTypeDescription
defaultbooleanInitial value before any decision (default false).
essentialbooleanAlways 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.
signalsPartial<Record<ConsentSignalKey, boolean>>Signals granted by this category.
title, description, icon, image, accentstringPresentation 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 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"); // true
cookies.getAll(); // { theme: "dark", ... } (prefix stripped)
cookies.remove("theme");

Extends CookieOptions with prefix.

OptionTypeDefaultDescription
prefixstring—Prepended to every cookie name; stripped by getAll().
pathstring"/"Cookie Path.
domainstring—Cookie Domain. Omitted by default (host-only).
expiresDate | number—Date or days-from-now.
maxAgenumber—Max-Age in seconds.
securebooleantrue on HTTPSAdds Secure.
sameSite"strict" | "lax" | "none""lax"SameSite attribute. none requires secure.
partitionedbooleanfalseCHIPS: requires secure; pair with sameSite: "none" in third-party contexts.
encode / decode(v: string) => stringURI codecCustom 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.

Attributes are normalized for every write (client and server):

  • No Domain attribute unless explicitly supplied.
  • __Host-<name> cookies require HTTPS, force Path=/, Secure, and drop any Domain attribute.
  • SameSite=None requires Secure; Partitioned also requires Secure. Invalid combinations are warned about in non-production builds.
  • Cookies older than seven days (or flagged server: true) should be set with a server Set-Cookie header 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",
});

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 ones

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

TypeDefinition
DefaultConsentCategory"necessary" | "preferences" | "analytics" | "marketing"
ConsentCategoryDefaultConsentCategory | (string & {}) — defaults are suggested, custom names allowed
ConsentState<C>Record<C, boolean>
ConsentCookieStateRecord<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
CookieOptionsOptions in the cookie table above
CookieManagerOptionsCookieOptions & { prefix?: string }
DisplayMeta{ title?, description?, icon?, image?, accent? }
ScriptRuleDisplayMeta & { src, execution?: "async" | "defer", attrs?, setsCookies? }
ManagedCookieDisplayMeta & { 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 }
ConsentSignalKeyThe four Google Consent Mode keys, plus any custom string
SameSite"strict" | "lax" | "none"

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.