Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set the Google Analytics cookie only after another consent cookie is set and "true"?

I am using React/Nextjs for my website and the react-cookie-consent library. It creates a pop up where the user can agree to the cookie policy. If agreed, a cookie is set: CookieConsent with value "true".

Additionally, I want to use Google Analytics to track users if they agree (click Accept on the popup).

But it doesnt work: The Google Analytic cookies _ga and G_ENABLED_IDPS are set before the user clicks on the pop up.

Funny thing is, I only realized that on the Microsoft Edge Browser. In Chrome, these cookies are not set before the user gives consent.

This is my current code in _document.js:

<Head>
          {/* Global Site Tag (gtag.js) - Google Analytics */}
          <script
            async
            src={`https://www.googletagmanager.com/gtag/js?id=${GA_TRACKING_ID}`}
          />
          <script
            dangerouslySetInnerHTML={{
              __html: `
            window.dataLayer = window.dataLayer || [];
            function gtag(){dataLayer.push(arguments);}            
            gtag('js', new Date());
            
          `}}
          />
          
          <script type="text/javascript" src="/static/blockReactDevTools.js" />
          
          <link href="https://fonts.googleapis.com/css?family=Cabin&display=swap" rel="stylesheet" />

</Head>

I played around using some hints from the internet, and came up with this version which also doesn't work:

<Head>
          {/* Global Site Tag (gtag.js) - Google Analytics */}
          <script 
            async
            src={`https://www.googletagmanager.com/gtag/js?id=${GA_TRACKING_ID}`}
          />

          <script        
            dangerouslySetInnerHTML={{
                __html: `
              
              var gtagId = '${GA_TRACKING_ID}';

              window['ga-disable-' + gtagId] = true;

              window.dataLayer = window.dataLayer || [];

              function gtag(){dataLayer.push(arguments);}   

              gtag('js', new Date());

              function getCookie(cname) {
                var name = cname + "=";
                var ca = document.cookie.split(';');
                for(var i = 0; i < ca.length; i++) {
                  var c = ca[i];
                  while (c.charAt(0) == ' ') {
                    c = c.substring(1);
                  }
                  if (c.indexOf(name) == 0) {
                    return c.substring(name.length, c.length);
                  }
                }
                return "";
              }

              window.addEventListener("load", function() {
                var isCookieConsentTrue = getCookie("CookieConsent") == 'true';

                if(isCookieConsentTrue){
                    window['ga-disable-' + gtagId] = false;
                    alert("Cookie Consent given!");
                    
                  }  else {
                    alert("Cookie Consent NOT given!");
                    window['ga-disable-' + gtagId] = true;
                  }
              });          
            
            `}}
          />

          <script type="text/javascript" src="/static/blockReactDevTools.js" />

          
          <link href="https://fonts.googleapis.com/css?family=Cabin&display=swap" rel="stylesheet" />

</Head>

I don't know if this is a nextjs specific issue, or something plain stupid general.

Can anyone guide me to a working solution?

EDIT: I tried the "Universal Analytics" approach of the suggestion. Suggested Solution make my helper functions to log events and pageviews fail (see below). Do I need also the gtag manager?

enter image description here

like image 634
flo Avatar asked Feb 11 '20 16:02

flo


People also ask

Does cookie consent affect Google Analytics?

Impact on Google Analytics information Google Analytics, such as Universal Analytics, typically uses cookies to identify users and their actions and attributes and requires cookie consent. This means that if a visitor opts out of cookies entirely, they won't be tracked as a visitor at all through analytics.

How are Google Analytics cookies set?

The cookie is created when the javascript library executes and is updated every time data is sent to Google Analytics. Used to store visitor-level custom variable data. This cookie is created when a developer uses the _setCustomVar method with a visitor level custom variable.

Are Google Analytics cookies first or third party?

Is Google Analytics a first party cookie? Google Analytics uses first-party cookies in a piece of Javascript that is added to every page in your website. This allows you to track behaviours on your site, however it relies on third-party cookies from third-party sites to scrape referral data.

Do I need a cookie consent banner for Google Analytics?

You must obtain the consent of your website users before placing a cookie on their devices to track them. Google Analytics uses cookies, which require that you have a cookie banner on your site to collect consent.


1 Answers

Use gtag's consent config options. Currently, the following can be put before any data measurement commands (config or event) are run in the header:

gtag('consent', 'default', {
  'ad_storage': 'denied',
  'analytics_storage': 'denied'
});

Then run this once the user has approved or if a consent cookie is present:

gtag('consent', 'update', {
  'ad_storage': 'granted',
  'analytics_storage': 'granted'
});

If you use Facebook Pixel, it works in a similar way. E.g. fbq('consent', 'revoke'); then fbq('consent', 'grant').

like image 104
Will Squire Avatar answered Oct 16 '22 07:10

Will Squire