Skip to main content

Gate GA4 on consent

Goal: keep your own GA4 setup code from running until the visitor consents to the analytics category, and run it the moment they do.

OptSens already integrates Google Consent Mode v2. The Google tag loads but stays denied until consent. This recipe is for the case where you inject your own gtag('config', ...) and want it to wait for consent.

Tag the config inline

Mark your GA4 config script with type="text/plain" and data-os-category="analytics". It will not execute until analytics is consented, then runs automatically.

<!-- The Google tag loads normally; Consent Mode holds it at denied -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXX"></script>

<!-- Your config waits for analytics consent -->
<script type="text/plain" data-os-category="analytics">
window.dataLayer = window.dataLayer || [];
function gtag(){ dataLayer.push(arguments); }
gtag('js', new Date());
gtag('config', 'G-XXXXXXX');
</script>

Replace G-XXXXXXX with your Measurement ID.

If your analytics setup lives in your application code, listen for the consent_update event instead:

OptSens.on('consent_update', function (consent) {
if (consent.analytics) {
gtag('config', 'G-XXXXXXX');
}
});

The consent_update event replays for late subscribers. This still runs if consent was already given before your code loaded. See Events.

Verify

  1. Open your site in a private window and reject analytics.
  2. In DevTools, confirm no collect request goes to Google Analytics.
  3. Open the preference center, accept analytics and save.
  4. The collect request now fires, and OptSens.hasConsent('analytics') returns true in the console.