Guides
Google Analytics + ConsentLayer
This guide shows how to load Google Analytics 4 only when statistics consent is given.
With the SDK (React)
import { ConsentGate } from '@consentlayer/sdk/react'
import Script from 'next/script' // or a regular script tag
function Analytics() {
return (
<ConsentGate category="statistics">
<Script src={`https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXX`} />
<Script id="gtag-init">
{`
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-XXXXXXXXX');
`}
</Script>
</ConsentGate>
)
}With the SDK (vanilla JS)
import { hasConsent, onConsentChange } from '@consentlayer/sdk'
function loadGA() {
if (hasConsent('statistics')) {
const script = document.createElement('script')
script.src = 'https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXX'
document.head.appendChild(script)
}
}
// Check on page load
loadGA()
// Also check when consent changes
onConsentChange(() => loadGA())Without the SDK (banner only)
If you are using just the banner script tag without the SDK, the banner's built-in script blocking handles Google Analytics automatically. The gtag script is blocked until statistics consent is given, then released.
No additional code is needed — the banner detects and manages GA scripts.