Loading auth config...
Skip to main content
Lokker
A visual representation of consent management in digital analytics, featuring symbols for GDPR and CCPA compliance, cookies, user consent buttons, and tracking technologies, illustrating the integration of Google Analytics with consent management platforms and the importance of privacy regulations in data tracking.

Google Analytics Consent Management Integration

Implementing Google Analytics with proper consent management is critical for privacy compliance. This guide provides detailed instructions for integrating Google Analytics with popular consent management platforms (CMPs) and ensuring analytics only runs when users have explicitly consented.

Table of Contents


Google Analytics cannot legally operate without explicit user consent due to:

  • GDPR requirements for personal data processing
  • CCPA/CPRA compliance for California residents
  • Court rulings declaring Google Analytics illegal without consent
  • Industry regulations (HIPAA, GLBA) for sensitive data

Critical Point: Google Analytics must either:

  • Run with explicit consent (user actively agrees)
  • Not run at all (user denies consent or doesn't respond)

Cannot legally operate in:

  • ❌ "Opt-out" mode
  • ❌ "Legitimate interest" basis
  • ❌ Pre-consent tracking
  • ❌ Implied consent scenarios

OneTrust Integration

1. OneTrust Configuration

// OneTrust cookie category configuration
// Category ID: C0002 (Analytics)
// Purpose: Website analytics and performance measurement
// Legal Basis: Consent required

OneTrust Script Integration

<!-- OneTrust Cookie Consent -->
<script src="https://cdn.cookielaw.org/scripttemplates/otSDKStub.js"
data-domain-script="your-domain-script-id"
type="text/javascript"
charset="UTF-8"></script>
<script type="text/javascript">
function OptanonWrapper() {
// Initialize Google Analytics only if consent is given
initializeGoogleAnalytics();
}
</script>

2. Conditional Google Analytics Loading

Basic Implementation

// Check OneTrust consent and load Google Analytics
function initializeGoogleAnalytics() {
// Check if user has consented to analytics (C0002)
if (OnetrustActiveGroups.includes('C0002')) {
console.log('Analytics consent given - loading Google Analytics');

// Load Google Analytics with privacy-safe configuration
gtag('config', 'GA_MEASUREMENT_ID', {
'anonymize_ip': true,
'allow_google_signals': false,
'allow_ad_personalization_signals': false,
'restricted_data_processing': true,
'cookie_flags': 'SameSite=Strict;Secure'
});

// Track initial page view
gtag('event', 'page_view', {
'page_path': window.location.pathname,
'page_title': document.title
});
} else {
console.log('No analytics consent - Google Analytics not loaded');
}
}

// Initialize when page loads
document.addEventListener('DOMContentLoaded', initializeGoogleAnalytics);
// Handle consent changes dynamically
function handleConsentChange() {
// Check current consent status
const hasAnalyticsConsent = OnetrustActiveGroups.includes('C0002');

if (hasAnalyticsConsent && !window.gaLoaded) {
// User just gave consent - load Google Analytics
loadGoogleAnalytics();
window.gaLoaded = true;
} else if (!hasAnalyticsConsent && window.gaLoaded) {
// User withdrew consent - disable Google Analytics
disableGoogleAnalytics();
window.gaLoaded = false;
}
}

// Listen for consent changes
document.addEventListener('OneTrustGroupsUpdated', handleConsentChange);

function loadGoogleAnalytics() {
// Load Google Analytics script
const script = document.createElement('script');
script.async = true;
script.src = 'https://www.googletagmanager.com/gtag/js?id=GA_MEASUREMENT_ID';
document.head.appendChild(script);

// Initialize with privacy settings
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());

gtag('config', 'GA_MEASUREMENT_ID', {
'anonymize_ip': true,
'allow_google_signals': false,
'allow_ad_personalization_signals': false,
'restricted_data_processing': true,
'cookie_flags': 'SameSite=Strict;Secure'
});
}

function disableGoogleAnalytics() {
// Disable Google Analytics tracking
if (window.gtag) {
gtag('config', 'GA_MEASUREMENT_ID', {
'send_page_view': false
});
}

// Clear existing cookies
document.cookie = '_ga=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;';
document.cookie = '_gid=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;';
document.cookie = '_gat=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;';
}

Cookiebot Integration

1. Cookiebot Configuration

Cookiebot Script Setup

<!-- Cookiebot Cookie Consent -->
<script id="Cookiebot" src="https://consent.cookiebot.com/uc.js"
data-cbid="your-cookiebot-id"
data-blockingmode="auto"
type="text/javascript"></script>

2. Conditional Loading with Cookiebot

Basic Implementation

// Check Cookiebot consent and load Google Analytics
function initializeGoogleAnalytics() {
// Check if user has consented to statistics cookies
if (Cookiebot.consent.statistics) {
console.log('Statistics consent given - loading Google Analytics');

// Load Google Analytics
gtag('config', 'GA_MEASUREMENT_ID', {
'anonymize_ip': true,
'allow_google_signals': false,
'allow_ad_personalization_signals': false,
'restricted_data_processing': true
});
} else {
console.log('No statistics consent - Google Analytics not loaded');
}
}

// Initialize when consent is available
if (typeof Cookiebot !== 'undefined') {
initializeGoogleAnalytics();
} else {
// Wait for Cookiebot to load
document.addEventListener('CookiebotOnConsentReady', initializeGoogleAnalytics);
}
// Handle Cookiebot consent changes
function handleCookiebotConsentChange() {
const hasStatisticsConsent = Cookiebot.consent.statistics;

if (hasStatisticsConsent && !window.gaLoaded) {
loadGoogleAnalytics();
window.gaLoaded = true;
} else if (!hasStatisticsConsent && window.gaLoaded) {
disableGoogleAnalytics();
window.gaLoaded = false;
}
}

// Listen for consent changes
document.addEventListener('CookiebotOnConsentReady', handleCookiebotConsentChange);
document.addEventListener('CookiebotOnDecline', handleCookiebotConsentChange);

CookieYes Integration

1. CookieYes Configuration

CookieYes Script Setup

<!-- CookieYes Cookie Consent -->
<script id="cookieyes" type="text/javascript"
src="https://cdn-cookieyes.com/client_data/your-client-id.js"></script>

2. Conditional Loading with CookieYes

// Check CookieYes consent and load Google Analytics
function initializeGoogleAnalytics() {
// Check if user has consented to analytics
if (window.cookieyes && window.cookieyes.consent && window.cookieyes.consent.analytics) {
console.log('Analytics consent given - loading Google Analytics');

gtag('config', 'GA_MEASUREMENT_ID', {
'anonymize_ip': true,
'allow_google_signals': false,
'allow_ad_personalization_signals': false,
'restricted_data_processing': true
});
} else {
console.log('No analytics consent - Google Analytics not loaded');
}
}

// Initialize when CookieYes is ready
if (window.cookieyes) {
initializeGoogleAnalytics();
} else {
document.addEventListener('cookieyes_consent_update', initializeGoogleAnalytics);
}
// Universal consent management integration
class ConsentManager {
constructor() {
this.consentGiven = false;
this.gaLoaded = false;
this.init();
}

init() {
// Check for various consent management platforms
this.checkOneTrust();
this.checkCookiebot();
this.checkCookieYes();
this.checkGenericConsent();

// Initialize Google Analytics if consent is given
if (this.consentGiven) {
this.loadGoogleAnalytics();
}
}

checkOneTrust() {
if (typeof OnetrustActiveGroups !== 'undefined') {
this.consentGiven = OnetrustActiveGroups.includes('C0002');
document.addEventListener('OneTrustGroupsUpdated', () => {
this.consentGiven = OnetrustActiveGroups.includes('C0002');
this.handleConsentChange();
});
}
}

checkCookiebot() {
if (typeof Cookiebot !== 'undefined') {
this.consentGiven = Cookiebot.consent.statistics;
document.addEventListener('CookiebotOnConsentReady', () => {
this.consentGiven = Cookiebot.consent.statistics;
this.handleConsentChange();
});
}
}

checkCookieYes() {
if (window.cookieyes && window.cookieyes.consent) {
this.consentGiven = window.cookieyes.consent.analytics;
document.addEventListener('cookieyes_consent_update', () => {
this.consentGiven = window.cookieyes.consent.analytics;
this.handleConsentChange();
});
}
}

checkGenericConsent() {
// Check for generic consent cookie
const consentCookie = this.getCookie('consent');
if (consentCookie) {
const consent = JSON.parse(consentCookie);
this.consentGiven = consent.analytics === true;
}
}

handleConsentChange() {
if (this.consentGiven && !this.gaLoaded) {
this.loadGoogleAnalytics();
} else if (!this.consentGiven && this.gaLoaded) {
this.disableGoogleAnalytics();
}
}

loadGoogleAnalytics() {
// Load Google Analytics with privacy-safe configuration
const script = document.createElement('script');
script.async = true;
script.src = 'https://www.googletagmanager.com/gtag/js?id=GA_MEASUREMENT_ID';
document.head.appendChild(script);

window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());

gtag('config', 'GA_MEASUREMENT_ID', {
'anonymize_ip': true,
'allow_google_signals': false,
'allow_ad_personalization_signals': false,
'restricted_data_processing': true,
'cookie_flags': 'SameSite=Strict;Secure'
});

this.gaLoaded = true;
console.log('Google Analytics loaded with consent');
}

disableGoogleAnalytics() {
// Disable Google Analytics
if (window.gtag) {
gtag('config', 'GA_MEASUREMENT_ID', {
'send_page_view': false
});
}

// Clear cookies
this.clearGACookies();
this.gaLoaded = false;
console.log('Google Analytics disabled - consent withdrawn');
}

clearGACookies() {
const cookies = ['_ga', '_gid', '_gat', '_gcl_au', '_gcl_aw'];
cookies.forEach(cookie => {
document.cookie = `${cookie}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;`;
document.cookie = `${cookie}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/; domain=.${window.location.hostname};`;
});
}

getCookie(name) {
const value = `; ${document.cookie}`;
const parts = value.split(`; ${name}=`);
if (parts.length === 2) return parts.pop().split(';').shift();
}
}

// Initialize consent manager
const consentManager = new ConsentManager();
  • No Analytics Loading: Verify Google Analytics doesn't load before consent
  • No Cookies Set: Confirm no Google Analytics cookies are created
  • No Network Requests: Check that no requests are sent to Google servers
  • Console Messages: Verify appropriate console messages are displayed

Post-Consent Testing

  • Analytics Loading: Confirm Google Analytics loads after consent
  • Cookies Created: Verify appropriate cookies are set
  • Network Requests: Check that requests are sent to Google servers
  • Privacy Settings: Confirm privacy-safe configuration is applied
  • Analytics Disabled: Verify Google Analytics stops tracking
  • Cookies Cleared: Confirm Google Analytics cookies are removed
  • No New Requests: Check that no new requests are sent
  • Re-consent: Test that analytics can be re-enabled with new consent

2. Browser Developer Tools Testing

Network Tab Verification

// Check for Google Analytics requests
// Before consent: No requests to google-analytics.com or googletagmanager.com
// After consent: Requests to google-analytics.com/g/collect
// After withdrawal: No new requests
// Check for Google Analytics cookies
// Before consent: No _ga, _gid, _gat cookies
// After consent: _ga, _gid cookies present
// After withdrawal: Cookies cleared

Console Testing

// Test consent status
console.log('OneTrust consent:', OnetrustActiveGroups.includes('C0002'));
console.log('Cookiebot consent:', Cookiebot.consent.statistics);
console.log('GA loaded:', window.gaLoaded);

Common Implementation Mistakes

❌ Dangerous Patterns

// DANGEROUS: Loading Google Analytics before consent
gtag('config', 'GA_MEASUREMENT_ID'); // ❌ Loads before consent check
// DANGEROUS: Assuming consent without explicit agreement
if (!localStorage.getItem('consent_denied')) {
gtag('config', 'GA_MEASUREMENT_ID'); // ❌ No explicit consent
}

3. Opt-Out Instead of Opt-In

// DANGEROUS: Opt-out approach
if (!localStorage.getItem('analytics_opt_out')) {
gtag('config', 'GA_MEASUREMENT_ID'); // ❌ Should be opt-in
}

✅ Correct Patterns

// CORRECT: Explicit consent required
if (OnetrustActiveGroups.includes('C0002')) {
gtag('config', 'GA_MEASUREMENT_ID', privacyConfig); // ✅ Explicit consent
}
// CORRECT: Handle consent changes
document.addEventListener('OneTrustGroupsUpdated', handleConsentChange);

3. Privacy-Safe Configuration

// CORRECT: Privacy-safe configuration
const privacyConfig = {
'anonymize_ip': true,
'allow_google_signals': false,
'restricted_data_processing': true
};

Industry-Specific Considerations

Healthcare Websites

HIPAA Compliance Requirements

// Healthcare: Additional privacy protections
const healthcareConfig = {
'anonymize_ip': true,
'allow_google_signals': false,
'allow_ad_personalization_signals': false,
'restricted_data_processing': true,
'send_page_view': false, // Manual tracking only
'data_retention': {
'mode': 'MONTHS',
'months': 14
}
};

Financial Services Websites

GLBA Compliance Requirements

// Financial: Enhanced security settings
const financialConfig = {
'anonymize_ip': true,
'allow_google_signals': false,
'allow_ad_personalization_signals': false,
'restricted_data_processing': true,
'cookie_flags': 'SameSite=Strict;Secure;HttpOnly',
'data_retention': {
'mode': 'MONTHS',
'months': 14
}
};

Conclusion

Proper consent management integration with Google Analytics is essential for privacy compliance. The key principles are:

  1. Explicit Consent Required: Never load Google Analytics without explicit user consent
  2. Consent Change Handling: Dynamically enable/disable based on consent changes
  3. Privacy-Safe Configuration: Always use privacy-protective settings
  4. Industry-Specific Rules: Apply additional protections for healthcare and financial sites
  5. Regular Testing: Continuously verify consent implementation works correctly

Rember: When in doubt, err on the side of caution. It's better to collect less data legally than to face privacy violations and legal consequences.


For additional support with consent management integration, consult with your legal team and consider implementing a comprehensive privacy management solution.