Consent Management for Analytics
What you'll learn: You'll implement conditional analytics loading that respects user consent and cookie preferences, ensuring legal compliance and user trust.
The Core Principle
Analytics scripts shouldn't load automatically on every visitor. Modern privacy laws (GDPR, CCPA) require explicit user consent before tracking. Conditional loading means your analytics code only initializes after the user grants permission—no tracking happens until they say "yes."
Think of it like a store asking permission before recording security footage of each customer. Until they agree, no cameras run.
Implementation Strategy
Before your analytics initialization, check consent status:
// Check consent before loading analytics
function initializeAnalytics() {
const consent = localStorage.getItem('analyticsConsent');
if (consent === 'granted') {
// Now safe to initialize GA4 or alternatives
gtag('consent', 'update', {
analytics_storage: 'granted'
});
// Track page view only after consent
gtag('event', 'page_view');
} else {
// Block analytics loading
console.log('Analytics blocked: No user consent');
}
}
// User grants consent via banner
function handleConsentAccept() {
localStorage.setItem('analyticsConsent', 'granted');
localStorage.setItem('consentTimestamp', Date.now());
initializeAnalytics();
}
// User denies consent
function handleConsentDeny() {
localStorage.setItem('analyticsConsent', 'denied');
// Ensure no tracking scripts load
}
For Google Analytics 4, set default consent to denied:
gtag('consent', 'default', {
analytics_storage: 'denied',
wait_for_update: 500
});
This prevents any data collection until explicitly updated. The pattern works with any analytics tool—check consent state before calling initialization functions.
Key Takeaway: Conditional analytics loading checks user consent before initializing tracking scripts, storing preferences persistently and only collecting data after explicit permission is granted.