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: {
trackingIds: [
"UA-XXXXXXXXX-X",
],
head: true,
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={() => {
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.