featured image

Cookies Consent Gdpr

How-to setup GDPR cookie consent with Gatsby using modules gatsby-plugin-gdpr-cookies and cookie-consent

2021-11-152 min read
Profile picture
👋
Developed and Written by: Donald Boulton🎉 0
|

Cookie Consent without External Scripts Dated: January 26, 2020

By Bojan Bedrač

Stackoverflow Explanation

General Data Protection Regulation (GDPR) imposes a couple of requirements on websites in regard to collecting and processing user data.

Simple tracking solutions like Google Analytics or Facebook Pixel can only be used in compliance when the users agree with their visits and actions being tracked.

To make your Gatsby site compliant there are two parts you need to implement.

Allow or prevent user data to be collected based on user choice. Give the user a choice to opt-in or opt-out to have their data collected.

CONTROL WHEN USERS DATA IS COLLECTED

To be compliant with GDPR, no user data can be collected unless the user gave an explicit consent. When it comes to tracking scripts that means the scripts can’t be activated before the user gives the consent.

A convenient Gatsby plugin takes care of this part. The gatsby-plugin-gdpr-cookies checks for two cookies that control if Google Analytics or Facebook Pixel scripts should be activated.

The cookies are named after the scripts gatsby-gdpr-google-analytics and gatsby-gdpr-facebook-pixel. When these cookies value is true the scripts are activated.

You can install the plugin using npm:

node
bash

To configure the plugin put the configuration in your gatsby-config.js:

gatsby-config.js
tsx

Giving the user a way to give consent for their data to be collected can be done by building your own form and setting the cookies (gatsby-gdpr-google-analytics and gatsby-gdpr-facebook-pixel).

If you’re using React in your Gatsby site, you can opt for a ready made solution react-cookie-consent.

The React component comes packaged in an npm module, so you can add it to your project by running:

node
bash

Cookie Consent Configuration

After that add the component in your layout.js file or wherever you define your layout. It’s important that the component is loaded on any page so the consent can be collected regardless of the entry page.

src/components/CookieConsent.tsx
tsx

Or Taylor it to you needs

src/components/CookieConsent.tsx
tsx

The important part is to set the cookieName prop to the value of the cookie you want to set (e.g.: gatsby-gdpr-google-analytics).

There are many props to configure the components behavior and appearance.

Quick tip When you want to set both cookies with one action, you can hook into the flow by using the onAccept and onDecline callbacks. You can set the cookies yourself by importing the Cookies (from js-cookie) like below:

src/components/CookieConsent.tsx
tsx

Hopefully this helped you making your Gatsby site GDPR compliant.

Cookie’s Explained In Privacy Page