5
votes

I have developed a website using gatsby and I am using google analytics plugin via gatsby-plugin-google-analytics, now to be nice with the users, I would like to add a cookie consent where the user will be two options whether to accept or decline cookies usages. If the user declines then I would like to stop google analytics to track the user activity. I dug into their documentation but unable to find the option to achieve this, is there any way around to achieve this.

{
  resolve: `gatsby-plugin-google-analytics`,
  options: {
    trackingId: siteConfig.googleAnalyticsId,
    // Defines where to place the tracking script - `true` in the head and `false` in the body
    head: false,
  },
},

For the movement my gatsby-config.js looks like this. how one can achieve this.

Thanks you in advance.

2

2 Answers

0
votes

The plugin merely loads the library and instruments page tracking calls in a Gatsby-compatible way for you. All of the other Google Analytics calls, including disabling measurement for a user works the same as normal.

It's up to you to:

  1. Build and show a cookie notice with an opt-out
  2. Remember when a user has opted out
  3. Communicate this on each page-load for the user (before any ga() calls are made) by setting window['ga-disable-UA-XXXXX-Y'] = true

You should be able to do this in a function exported as onClientEntry from gatsby-browser.js. For example:

export const onClientEntry = () => {
  if (userHasOptedOutOfThirdPartyTracking()) {
    window[`ga-disable-${process.env.GATSBY_GOOGLE_ANALYTICS_ID`] = true
  }
}
0
votes

For the Gatsby website, you could use a combination of gatsby-plugin-gdpr-cookies for analytics cookies management in your gatsby-config.js and react-cookie-consent to display the cookie banner.

# using npm
npm install --save gatsby-plugin-gdpr-cookies react-cookie-consent

# using yarn
yarn add gatsby-plugin-gdpr-cookies react-cookie-consent

You can find a more detailed tutorial here.