Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to configure gatsby-plugin-google-analytics with cookies consent?

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.

like image 438
Mr. Pyramid Avatar asked Nov 06 '22 14:11

Mr. Pyramid


1 Answers

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
  }
}
like image 84
coreyward Avatar answered Nov 14 '22 08:11

coreyward