I've set up Google Analytics with the gatsby-pluging-google-gtag plugin with programmatic opt-out like so:
1. Install the plugin
npm install gatsby-plugin-google-gtag
2. Add plugin to your gatsby-config.js
{
resolve: `gatsby-plugin-google-gtag`,
options: {
// You can add multiple tracking ids and a pageview event will be fired for all of them.
trackingIds: [
"UA-XXXXXXXXX-X", // Google Analytics / GA
],
// puts tracking script in the head instead of the body
head: true,
// enable ip anonymization (relevant for GDPR)
anonymize: true,
},
},
3. Add button in privacy page to allow a user to opt out of Google Analytics
To programmatically opt out a person from Google Analytics, you need to set an opt out cookie in the onClick
handler of your button.
<button onClick={() => {
// TODO: replace UA-XXXXXXXXX-X with your tracking id. Make sure to not delete any other characters
document.cookie = "ga-disable-UA-XXXXXXXXX-X=true; expires=Thu, 31 Dec 2099 23:59:59 UTC;path=/";
window.disableStr = 1;
alert("opt out successful");
}}>
The onClick
handler basically does pretty much the same as Gatsby suggests in their documentation
Please note that you need to replace the UA-XXXXXXXXX-X
with the proper tracking id from your Google Analytics admin panel. You might also consider using an env var for the tracking id to keep the code base DRY
.
Caveats
The plugin does not load Google Analytics when you run:
gatsby develop
You need to run
gatsby build && gatsby serve
Please also make sure that your browser does not block the analytics script from the start (e.g. Brave browser). Otherwise, it won't work. After you have clicked the button you should see an additional cookie in the developer console.