Core API
Framework-agnostic functions for reading consent state. Import from @consentlayer/sdk.
All functions are stateless — they read the cl_consent cookie each time they are called. No initialization required.
hasConsent
Check if a specific cookie category has consent.
import { hasConsent } from '@consentlayer/sdk'
if (hasConsent('statistics')) {
// Safe to load analytics
gtag('config', 'G-XXXXXXXXX')
}Parameters:
category(string) — The category slug to check (e.g.,"statistics","marketing")
Returns: boolean — true if consented, false if not consented or no consent cookie exists.
getConsentState
Get the full consent state object.
import { getConsentState } from '@consentlayer/sdk'
const state = getConsentState()
if (state) {
console.log(state.categories) // { essential: true, statistics: false, marketing: false }
console.log(state.jurisdiction) // "gdpr" | "ccpa" | "none"
console.log(state.version) // 1
console.log(state.gpcSignal) // false
}Returns: ConsentState | null — Returns null if no consent cookie exists.
ConsentState type
interface ConsentState {
version: number
timestamp: number
jurisdiction: 'gdpr' | 'ccpa' | 'none'
gpcSignal: boolean
doNotSell: boolean
categories: Record<string, boolean>
}onConsentChange
Subscribe to consent changes. Fires when the visitor interacts with the banner.
import { onConsentChange } from '@consentlayer/sdk'
const unsubscribe = onConsentChange((state) => {
if (state.categories.statistics) {
loadAnalytics()
}
})
// Later: stop listening
unsubscribe()Parameters:
callback(function) — Called with the newConsentStatewhen consent changes
Returns: () => void — Unsubscribe function
showPreferences
Re-open the consent preferences modal so the visitor can change their choices.
import { showPreferences } from '@consentlayer/sdk'
document.querySelector('#manage-cookies').addEventListener('click', () => {
showPreferences()
})hasConsentCookie
Check if a valid consent cookie exists.
import { hasConsentCookie } from '@consentlayer/sdk'
if (!hasConsentCookie()) {
// First visit — consent banner will appear
}Returns: boolean
getJurisdiction
Get the detected jurisdiction from the consent cookie.
import { getJurisdiction } from '@consentlayer/sdk'
const jur = getJurisdiction() // "gdpr" | "ccpa" | "none"Returns: "gdpr" | "ccpa" | "none" — Returns "none" if no consent cookie exists.