ConsentStackDocs

JavaScript API

Complete API reference for the ConsentStack JavaScript SDK.

Once the ConsentStack script loads, the full API is available at window.consentstack. Use it to read consent state, set consent programmatically, listen for changes, and control the banner and preferences UI.

TypeScript types

The key types you will work with:

// Consent state — a map of category ID to granted/denied
type ConsentCategories = Record<string, boolean>
// Example: { essential: true, analytics: false, marketing: false }

// SDK event names
type ConsentEventType =
  | "ready"
  | "consent"
  | "error"
  | "preferences:open"
  | "preferences:close"

// Event payloads
type ConsentEventData = {
  ready: { config: ConsentConfig | null; consent: Record<string, boolean> | null }
  consent: Record<string, boolean>
  error: Error
  "preferences:open": undefined
  "preferences:close": undefined
}

// Full config object (returned by getConfig)
interface ConsentConfig {
  appearance: Appearance
  content: Content
  categories: ConsentCategory[]
  showReentryButton: boolean
}

These methods let you read and write consent state directly.

getConsent()

Returns the visitor's current consent choices, or null if they have not made a decision yet.

getConsent(): Record<string, boolean> | null
const consent = window.consentstack.getConsent()

if (consent) {
  console.log("Analytics allowed:", consent.analytics)
} else {
  console.log("No consent decision yet")
}

setConsent()

Sets consent programmatically. This saves the decision to local storage, logs it to the ConsentStack server, activates or blocks scripts accordingly, and hides the banner.

setConsent(categories: Record<string, boolean>): Promise<void>
ParameterTypeDescription
categoriesRecord<string, boolean>A map of category IDs to true (granted) or false (denied).
// Grant analytics, deny marketing
await window.consentstack.setConsent({
  essential: true,
  analytics: true,
  marketing: false,
})

If this is the visitor's first consent decision, it is logged as an initial event. Subsequent calls are logged as update events. If you revoke a previously granted category, the SDK shows a refresh prompt since already-executed scripts cannot be undone.

hasConsent()

Checks whether a specific category is currently granted. Returns false if the visitor has not made a decision yet.

hasConsent(category: string): boolean
if (window.consentstack.hasConsent("analytics")) {
  loadCustomAnalytics()
}

onConsentChange()

Subscribes to consent changes. Your callback fires every time consent is set or updated — from the banner, preferences panel, or a setConsent() call. Returns an unsubscribe function.

onConsentChange(
  callback: (consent: Record<string, boolean>) => void
): () => void
const unsubscribe = window.consentstack.onConsentChange((consent) => {
  if (consent.analytics) {
    initAnalytics()
  }
})

// Later, stop listening
unsubscribe()

UI operations

Control the consent banner and preferences panel from your own code.

showBanner()

Displays the consent banner. In the default banner mode, the SDK shows the banner automatically for new visitors. Use this method to re-show it manually — for example, in headless mode where you handle the UI trigger yourself.

showBanner(): void
document.getElementById("manage-cookies").addEventListener("click", () => {
  window.consentstack.showBanner()
})

showPreferences()

Opens the preferences panel where visitors can toggle individual consent categories.

showPreferences(): void
// Open preferences from a footer link
document.getElementById("cookie-settings").addEventListener("click", () => {
  window.consentstack.showPreferences()
})

You can also open preferences by navigating to #cs-preferences — the SDK listens for this hash automatically.

hidePreferences()

Closes the preferences panel programmatically. Emits a preferences:close event and re-shows the re-entry button if the visitor has already made a consent decision.

hidePreferences(): void

isPreferencesOpen()

Returns whether the preferences panel is currently visible.

isPreferencesOpen(): boolean
if (!window.consentstack.isPreferencesOpen()) {
  window.consentstack.showPreferences()
}

Events

Subscribe to SDK lifecycle events for fine-grained control over your integration.

on()

Subscribes to a named SDK event. Returns an unsubscribe function.

on<T extends ConsentEventType>(
  event: T,
  callback: (data: ConsentEventData[T]) => void
): () => void
EventPayloadFires when
"ready"{ config, consent }SDK has initialized and config is loaded.
"consent"Record<string, boolean>Consent state changes (same as onConsentChange).
"error"ErrorAn SDK error occurs.
"preferences:open"undefinedPreferences panel opens.
"preferences:close"undefinedPreferences panel closes.
// Wait for the SDK to be ready before reading state
const unsubscribe = window.consentstack.on("ready", ({ config, consent }) => {
  console.log("SDK ready. Region categories:", config?.categories)
  console.log("Current consent:", consent)
  unsubscribe()
})

// Track when users open preferences
window.consentstack.on("preferences:open", () => {
  analytics.track("consent_preferences_opened")
})

Configuration

getConfig()

Returns the loaded consent configuration object, or null if the SDK has not finished initializing. The config includes appearance settings, content strings, category definitions, and re-entry button settings.

getConfig(): ConsentConfig | null
const config = window.consentstack.getConfig()

if (config) {
  console.log("Categories:", config.categories.map(c => c.name))
  console.log("Layout:", config.appearance.layout)
}

debug()

Prints SDK state to the browser console — site key, mode, current consent, and config version. Pass { verbose: true } to include the full config and state objects.

debug(options?: { verbose?: boolean }): void
// Quick overview
window.consentstack.debug()

// Full state dump
window.consentstack.debug({ verbose: true })

Waiting for the SDK

The SDK initializes asynchronously. If your code runs before the script has loaded, window.consentstack will be undefined. Use the ready event or a guard check:

// Option 1: Guard check
if (window.consentstack) {
  const consent = window.consentstack.getConsent()
}

// Option 2: Wait for ready event
function onSdkReady() {
  window.consentstack.on("ready", ({ consent }) => {
    console.log("Consent state:", consent)
  })
}

if (window.consentstack) {
  onSdkReady()
} else {
  // Poll until available
  const interval = setInterval(() => {
    if (window.consentstack) {
      clearInterval(interval)
      onSdkReady()
    }
  }, 50)
}

What's next