0
votes

I've spent multiple days right now researching and trying different things out to get this running. But nothing of the ways worked out so far for me.

My current setup is:

gatsby-config.js

module.exports = {
  plugins: [
    {
      resolve: `gatsby-plugin-gtag`,
      options: {
        trackingId: "G-TRACKING ID",
        head: true,
        anonymize: true
      },
    },
    {
      resolve: `gatsby-plugin-gdpr-cookies`,
      options: {
        googleAnalytics: {
          trackingId: "G-TRACKING ID",
          cookieName: "gatsby-gdpr-google-analytics",
          anonymize: true,
        },
      },
      environments: ["development", "production"],
    },
    ...
  ]
}

In src/pages/index.js

import React from "react"
import CookieConsent from "react-cookie-consent"

export default function Home() {

  return (
    <div>
      <CookieConsent
        overlay
        location="bottom"
        buttonText="Accept"
        enableDeclineButton
        declineButtonText="Decline"
        cookieName="gatsby-gdpr-google-analytics"
      >
        We are using cookies to enhance this site ...
      </CookieConsent>
      ...
    </div>
  )
}

The result is that the tracking works but when the user hits declined the tracking continues.

Is there a current way to set up google-analytics and a cookie consent that stops the tracking when the user declines it?

Thank you a lot in advance !

1

1 Answers

0
votes

Let’s say a visitor chooses to opt-out of Google Analytics tracking (this works for both analytics.js and gtag.js). You’ll then need to activate a browser window property to disable tracking. Before gtag() starts tracking behavior on your website, it always checks if the following is set.

window['ga-disable-<GA_TRACKING_ID>'] = true;

The biggest advantage is that you don’t have to remove the Tracking Code from the web pages. But the window property must be set before the tracking code makes any calls.

<!-- Google Analytics -->
<script>
window['ga-disable-<GA_TRACKING_ID>'] = true;
    
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=GA_MEASUREMENT_ID"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', '<GA_TRACKING_ID>');
</script>

In the example above, no information will be sent to GA because window['ga-disable-<GA_TRACKING_ID>'] is set to true before the GA code snippet. You only need to think of a logic that will set it to true when someone has clicked Decline.

NOTE: This window property must be set before any calls to gtag() are made, and it must be set on each page for which you want to disable Analytics. If the property is not set or set to false, then Analytics will work as usual.