Privacy-friendly analytics in GatsbyJS
Tags: analytics, cookieconsent, gatsby, privacy
Published: 2021-06-17 22:36:44

---
title: Privacy-friendly analytics in GatsbyJS
published: true
date: 2021-06-17 00:00:00 UTC
tags: Analytics,CookieConsent,GatsbyJS,Privacy
series: Building a developer blog with GatsbyJS
canonical_url: https://MihaiBojin.com/personal-site/privacy-friendly-analytics-in-gatsbyjs
---

![Photo: Privacy please!](https://MihaiBojin.com/static/e7ec7a4b8e08865a1489f321aa4a5831/061a6/jason-dent-JFk0dVyvdvw-unsplash.jpg)<figcaption>"Photo by <a href="https://unsplash.com/@jdent?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Jason Dent</a> on <a href="https://unsplash.com/s/photos/privacy?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a>"</figcaption>

🔔 This article was originally posted on my site, [MihaiBojin.com](https://MihaiBojin.com/personal-site/privacy-friendly-analytics-in-gatsbyjs?utm_source=external&utm_medium=organic&utm_campaign=rss "MihaiBojin.com"). 🔔

* * *

For my site, I wanted to capture user analytics without tracking users' who don't want to be tracked. Here in Europe, the General Data Protection Regulation (GDPR) protects consumers' privacy. In particular, the [ePrivacy directive](https://gdpr.eu/cookies/) requests users' consent before setting any tracking cookies.

A quick search revealed [gatsby-plugin-gdpr-cookies](https://github.com/andrezimpel/gatsby-plugin-gdpr-cookies), a plugin that supports [Google Analytics](https://analytics.google.com/analytics/web/), [Google Tag Manager](https://marketingplatform.google.com/about/tag-manager/), and [Facebook Pixel](https://www.facebook.com/business/help/742478679120153?id=1205376682832142&helpref=faq_content).

In short, it provides a mechanism for asking the user to explicitly consent to any cookies being set; precisely what I needed!

## [<svg aria-hidden="true" focusable="false" height="16" version="1.1" viewbox="0 0 16 16" width="16"><path fill-rule="evenodd" d="M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z"></path></svg>](#installing-the-plugin)Installing the plugin

I installed the plugin with `npm install gatsby-plugin-gdpr-cookies` then added it to my `gatsby-config.js` file:

```
module.exports = {
  plugins: [
    {
      resolve: `gatsby-plugin-gdpr-cookies`,
      options: {
        googleAnalytics: {
          trackingId: /*GA_TRACKING_ID*/,
          cookieName: "gatsby-gdpr-google-analytics",
          anonymize: true, // https://github.com/andrezimpel/gatsby-plugin-gdpr-cookies#anonymize
          allowAdFeatures: false,
        },
      },
    },
  ],
};
```

Then, nothing...

It turns out configuring this plugin is a bit more cumbersome than [the documentation indicates](https://github.com/andrezimpel/gatsby-plugin-gdpr-cookies#initialize-and-track).

The plugin **requires you to set the cookie named `cookieName`** , for example: `gatsby-gdpr-google-analytics=true`, to enable tracking.

This was not immediately obvious, and I ended up spending unnecessary time to figure out why it wasn't working.

## [<svg aria-hidden="true" focusable="false" height="16" version="1.1" viewbox="0 0 16 16" width="16"><path fill-rule="evenodd" d="M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z"></path></svg>](#integrating-with-the-consent-banner)Integrating with the consent banner

With that out of the way, I needed a toggle to track if users had already accepted the banner. Typically, I'd have used another cookie - but that would defeat the purpose.

**Local storage to the rescue!** I found [Josh Comeau's excellent tutorial on sticky-state](https://www.joshwcomeau.com/snippets/react-hooks/use-sticky-state/) and implemented it.

A simple React component later, and some [TailwindUI code for the banner](https://tailwindui.com/components/marketing/elements/banners#component-39dd57897ef8e6d37aa07fbbafc188b1) and it was ready to go!

Here's the resulting code (simplified):

```
import * as React from 'react';
import { useLocation } from '@reach/router';
import { initializeAndTrack } from 'gatsby-plugin-gdpr-cookies';

function isBrowser() {
  return typeof window !== 'undefined';
}

function getValue(key, defaultValue) {
  return isBrowser() && window.localStorage.getItem(key)
    ? JSON.parse(window.localStorage.getItem(key))
    : defaultValue;
}

function setValue(key, value) {
  window.localStorage.setItem(key, JSON.stringify(value));
}

function useStickyState(defaultValue, key) {
  const [value, setter] = React.useState(() => {
    return getValue(key, defaultValue);
  });

  React.useEffect(() => {
    setValue(key, value);
  }, [key, value]);

  return [value, setter];
}

const CookieConsent = () => {
  const location = useLocation();
  if (isBrowser()) {
    initializeAndTrack(location);
  }

  const [bannerHidden, setBannerHidden] = useStickyState(
    false,
    'consentCookieHidden',
  );

  const EnableAnalytics = () => {
    document.cookie = 'gatsby-gdpr-google-analytics=true';
    setBannerHidden(true);
  };

  return (
    <>
      {!bannerHidden && (
        <div>
          <span>
            We use cookies to personalize content and analyze our
            traffic.
          </span>
          <button onClick={EnableAnalytics}>OK</button>
        </div>
      )}
    </>
  );
};

export default CookieConsent;
```

The final thing left is to call this component in the site's footer.

```
import CookieConsent from 'cookie-consent';
...
<CookieConsent/>
```

This ensures no analytics code is run and no cookies are set until the user clicks OK.

And that's it! This is how you can get your users' consent before enabling analytics and tracking cookies!

* * *

If you liked this article and want to read more like it, [please subscribe to my newsletter](https://motivated-founder-807.ck.page/db1cf284bf "newsletter link"); I send one out every few weeks!