Core API
Exports
Section titled “Exports”createConsent()
Section titled “createConsent()”function createConsent<TCategories extends Record<string, CategoryConfig>>( userConfig: ConsentConfig<TCategories>): ConsentInstance<TCategories>;Creates a new consent instance. This is the main entry point — everything starts here.
import { createConsent } from "@uabcodus/consent/core";
const consent = createConsent({ categories: { necessary: { readOnly: true }, analytics: {} } as const});parseConsentCookie()
Section titled “parseConsentCookie()”function parseConsentCookie(cookieString: string | undefined | null): CookieValue | null;Decodes and validates a consent cookie string. Returns null if the cookie is missing, malformed,
or missing a valid consentId. Useful for SSR hydration.
import { parseConsentCookie } from "@uabcodus/consent/core";
const cookie = parseConsentCookie(cookies().get("cc_cookie"));// CookieValue | nullisBot()
Section titled “isBot()”function isBot(): boolean;Returns true if the current user agent matches known bot/crawler patterns. Checks
navigator.userAgent against a regex and navigator.webdriver.
googleConsentMode
Section titled “googleConsentMode”const googleConsentMode: ConsentConfig<Record<string, CategoryConfig>>;A preset for Google Consent Mode v2. See the presets guide for usage.
syncGtagConsent()
Section titled “syncGtagConsent()”function syncGtagConsent(consent: ConsentInstance<Record<string, CategoryConfig>>): () => void;Subscribes to consent changes and syncs them to window.gtag("consent", "update", ...).
Returns an unsubscribe function. See Google Consent Mode.
ConsentConfig
Section titled “ConsentConfig”The configuration object passed to createConsent().
| Option | Type | Default | Description |
|---|---|---|---|
preset |
Partial<ConsentConfig> |
— | Base config to merge into. See Presets. |
mode |
"opt-in" | "opt-out" |
"opt-in" |
Consent strategy. |
revision |
number |
0 |
Policy revision. Set > 0 to enable revision checking. |
hideFromBots |
boolean |
true |
Skip consent for bots/crawlers. |
manageScripts |
boolean |
false |
Intercept <script data-category="..."> elements. |
scriptType |
string |
"text/consent" |
Blocked script type for deferred execution. |
autoClearCookies |
boolean |
true |
Auto-erase cookies for rejected categories. |
categories |
Record<string, CategoryConfig> |
(required) | Category definitions. |
storage |
StorageAdapter |
— | Storage adapter for persisting consent. |
initialCookie |
CookieValue | string | null |
— | Pre-seed consent (for SSR hydration). |
callbacks |
ConsentCallbacks |
— | Lifecycle callbacks. |
ConsentInstance
Section titled “ConsentInstance”Returned by createConsent(). The main API object you interact with.
.state
Section titled “.state”readonly state: ConsentStateThe current consent state. Readonly snapshot — use the methods below to modify consent.
consent.state.valid; // booleanconsent.state.skipped; // boolean — true if consent was skipped (bot)consent.state.mode; // "opt-in" | "opt-out"consent.state.acceptType; // "all" | "necessary" | "custom"consent.state.categories; // { [name]: { accepted: boolean; readOnly: boolean } }consent.state.services; // { [category]: { [service]: boolean } }consent.state.cookie; // CookieValue | null.accept()
Section titled “.accept()”accept( categories: CategoryAcceptArg<TCategories>, excludedCategories?: string[]): voidAccept categories. Accepts "all", "necessary", a single category name string, or an array
of category names.
consent.accept("all"); // Accept everythingconsent.accept("necessary"); // Accept only readOnly categoriesconsent.accept("analytics"); // Accept a single categoryconsent.accept(["analytics", "marketing"]); // Accept multipleconsent.accept("all", ["marketing"]); // Accept all except marketing.reject()
Section titled “.reject()”reject(categories: CategoryAcceptArg<TCategories>): voidReject categories. ReadOnly categories are protected — rejecting them has no effect.
consent.reject("marketing");consent.reject(["analytics", "marketing"]);consent.reject("all"); // Rejects everything except readOnly categories.acceptedCategory()
Section titled “.acceptedCategory()”acceptedCategory(category: CategoryNames<TCategories>): booleanReturns true if a category is currently accepted.
consent.acceptedCategory("analytics"); // true | false.acceptService()
Section titled “.acceptService()”acceptService( service: ServiceAcceptArg<TCategories, CategoryNames<TCategories>>, category: CategoryNames<TCategories>): voidAccept a service within a category. Accepting at least one service automatically accepts the parent category.
consent.acceptService("googleAnalytics", "analytics");consent.acceptService("all", "analytics"); // All services in analyticsconsent.acceptService(["ga4", "plausible"], "analytics");.rejectService()
Section titled “.rejectService()”rejectService( service: ServiceAcceptArg<TCategories, CategoryNames<TCategories>>, category: CategoryNames<TCategories>): voidReject a service within a category. Rejecting all services in a category automatically rejects the category.
consent.rejectService("facebookPixel", "marketing");.acceptedService()
Section titled “.acceptedService()”acceptedService( service: ServiceNames<TCategories, CategoryNames<TCategories>>, category: CategoryNames<TCategories>): booleanReturns true if a service within a category is accepted.
consent.acceptedService("googleAnalytics", "analytics"); // true | false.eraseCookies()
Section titled “.eraseCookies()”eraseCookies( cookies: string | RegExp | Array<string | RegExp>, path?: string, domain?: string): voidErase cookies matching names or patterns. Path and domain default to your cookie config.
consent.eraseCookies("_ga");consent.eraseCookies(/^_ga/);consent.eraseCookies(["_ga", "_gid", /^_gat/]);consent.eraseCookies("_ga", "/subdir", ".example.com");.getCookie()
Section titled “.getCookie()”getCookie(field?: string): unknownRead the current consent cookie value. Pass a field to get a specific field.
consent.getCookie(); // Full CookieValueconsent.getCookie("categories"); // string[]consent.getCookie("consentId"); // stringconsent.getCookie("data"); // unknown.setCookieData()
Section titled “.setCookieData()”setCookieData(props: { value: unknown; mode: "set" | "update" }): booleanStore custom data in the consent cookie. Returns true if data actually changed.
// Replaceconsent.setCookieData({ value: { userId: "123" }, mode: "set" });
// Merge (shallow for objects)consent.setCookieData({ value: { theme: "dark" }, mode: "update" });.getConfig()
Section titled “.getConfig()”getConfig<K extends string>(field?: K): unknownRead the resolved config (with defaults applied).
consent.getConfig(); // Full ConsentConfigResolvedconsent.getConfig("mode"); // "opt-in" | "opt-out"consent.getConfig("categoryNames"); // string[].validConsent()
Section titled “.validConsent()”validConsent(): booleanReturns true if consent is currently valid.
consent.validConsent(); // true | false.loadScript()
Section titled “.loadScript()”loadScript( src: string, attrs?: Record<string, string>): Promise<boolean>Dynamically load an external script. Returns a promise that resolves to true on success,
false on failure. Won’t load duplicate scripts (checked by src).
await consent.loadScript("https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX");await consent.loadScript("https://example.com/script.js", { async: "", id: "my-script"});.reset()
Section titled “.reset()”reset(deleteCookie?: boolean): voidReset the consent instance to its initial state. If deleteCookie is true, the consent cookie
is also removed.
consent.reset(); // Reset state onlyconsent.reset(true); // Reset state and delete the cookie.subscribe()
Section titled “.subscribe()”subscribe( listener: (state: Readonly<ConsentState>) => void): () => voidSubscribe to state changes. Returns an unsubscribe function.
const unsub = consent.subscribe((state) => { console.log("Consent state changed:", state);});
// Laterunsub();on( event: string, listener: (...args: unknown[]) => void): () => voidListen for events. Returns an unsubscribe function.
const unsub = consent.on("change", ({ cookie }) => { console.log("Changed:", cookie);});.off()
Section titled “.off()”off( event: string, listener: (...args: unknown[]) => void): voidRemove an event listener.
const listener = (data) => { /* ... */};consent.on("change", listener);consent.off("change", listener);.destroy()
Section titled “.destroy()”destroy(): voidDestroy the consent instance. Clears all subscriptions and event listeners. The instance should
not be used after calling destroy().
ConsentState
Section titled “ConsentState”The read-only state exposed by consent.state.
| Field | Type | Description |
|---|---|---|
valid |
boolean |
Whether consent has been given. |
skipped |
boolean |
Whether consent was skipped (bot detected). |
categories |
Record<string, { accepted: boolean; readOnly: boolean }> |
Per-category acceptance state. |
services |
Record<string, Record<string, boolean>> |
Per-service acceptance state. |
cookie |
CookieValue | null |
The current consent cookie data. |
mode |
"opt-in" | "opt-out" |
The configured consent mode. |
acceptType |
"all" | "necessary" | "custom" |
The type of the current acceptance. |
Events
Section titled “Events”| Event | Payload | When |
|---|---|---|
"firstConsent" |
{ cookie: CookieValue } |
First consent action (once per user) |
"consent" |
{ cookie: CookieValue } |
Consent given or restored from cookie |
"change" |
{ cookie: CookieValue } |
Categories or services changed |
These match the config callbacks.onFirstConsent, callbacks.onConsent, and callbacks.onChange.