Home > Back-end >  Google Consent Mode Implementation using Gatsby
Google Consent Mode Implementation using Gatsby

Time:06-29

I am following this tutorial about implementing google consent mode to add cookies to my website ! By using Gatsby.js I am not sure how to add these codes :

<!-- The initial config of Consent Mode -->
<script type="text/javascript">
window.dataLayer = window.dataLayer || [];
function gtag() {
dataLayer.push(arguments);
}
gtag('consent', 'default', {
ad_storage: 'denied',
analytics_storage: 'denied',
wait_for_update: 1500,
});
gtag('set', 'ads_data_redaction', true);
</script>
​
<!-- Cookie Information Pop-up Script is required for the SDK -->
<script id="CookieConsent" src="https://policy.app.cookieinformation.com/uc.js" data-culture="EN" type="text/javascript"></script>
​
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=TRACKING-ID"></script>
<script type="text/javascript">
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
​
gtag('config', 'TRACKING-ID');
</script>
​
</head>
<body>

Do you have any idea how to implement this code in Gatsby , is there any library or something that will help to implement these scripts ! Thanks

CodePudding user response:

Use this plugin from the Gatsby Plugin Hub gatsby-plugin-gdpr-cookies

It will provide you what you are looking for and also you can list in the options for the plugin which cookies you are looking to track a cookieName you wish to provide which you can then work with from a component level when creating a cookie toolbar such as:

{
  resolve: `gatsby-plugin-gdpr-cookies`,
  options: {
    googleAnalytics: {
      trackingId: process.env.UA_TAG, // your UA tag goes here
      cookieName: `gatsby-gdpr-google-analytics`,
      anonymize: true,
      allowAdFeatures: false
    },
    environments: [`production`, `development`]
  },
},

It elimites the usage of having to inject a script into the head of the website with React-Helmet as the plugin will handle the script injection for you.

CodePudding user response:

This component is used as the initial screen that applies when the page loads.

import React, { useState, useEffect } from 'react';

import { useLocation } from '@reach/router';
import { initializeAndTrack } from 'gatsby-plugin-gdpr-cookies';
import Cookies from 'js-cookie';

import CookieSettings from './Settings';

const CookieBanner = () => {
    const [showBanner, setShowBanner] = useState(false);
    const [showSettings, setShowSettings] = useState(false);
    const location = useLocation();

    // showSettings -> use this state property to open a configuration
    // window which may open up more information on the cookie(s) being applied

    useEffect(() => {
        setShowBanner(Cookies.get('gatsby-gdpr-responded') !== 'true');
    }, [])

    useEffect(() => {
        initTracking();
    }, [Cookies.get('gatsby-gdpr-responded')])

    const initTracking = () => {
        initializeAndTrack(location)
    }

    const handleAccept = () => {
        Cookies.set('gatsby-gdpr-google-analytics', true, { expires: 365 })
        handleCloseAll();
    }

    const handleDecline = () => {
        Cookies.remove('gatsby-gdpr-google-analytics');
        handleCloseAll();
    }

    const handleCloseAll = () => {
        setShowSettings(false);
        setShowBanner(false);

        Cookies.set('gatsby-gdpr-responded', true, { expires: 365 });
    }

    return (
        // add your component logic here
        // Take not of the different functions that are available above, like handleAccept / handleDecline / handleCloseAll 
        // handleCloseAll -> if a user declines / closes the banner
        // handleAccept -> a button to accept by default
        // handleDecline -> a button to decline the cookies

    )
}

export default CookieBanner

The next component is more of a Configuration screen, which provides more information on the cookies being applied, if you take note on the import of Toggle, we use a toggle to allow users to specifically toggle on or off their cookies at any point, you of course if you have many GDPR compliances, may want to either create separate functions that handle the removal of cookies or a reusable function that is passed the name of the cookie to be removed / applied.

import React, { useState } from 'react';

import Cookies from 'js-cookie';

import Button from '@components/Button';
import Toggle from '@components/Inputs/Toggle';

const CookieSettings = ({
    handleAccept,
    handleDecline,
    initTracking,
    handleCloseAll
}) => {
    const [trackAnalytics, setTrackAnalytics] = useState(Cookies.get('gatsby-gdpr-google-analytics') === 'true')

    const handleToggle = () => {
        Cookies.set('gatsby-gdpr-responded', true, { expires: 365 });

        setTrackAnalytics((prevState) => {
            if (prevState) {
                Cookies.remove('gatsby-gdpr-google-analytics');
            } else {
                Cookies.set('gatsby-gdpr-google-analytics', true, { expires: 365 })
            }

            return !prevState
        })

        initTracking();
    }

    return (
        // your JSX code here
    )
}

export default CookieSettings;
  • Related