Coder Social home page Coder Social logo

andrezimpel / gatsby-plugin-gdpr-cookies Goto Github PK

View Code? Open in Web Editor NEW
96.0 96.0 68.0 504 KB

Gatsby plugin to add Google Analytics (V4 is supported), Google Tag Manager, Facebook Pixel, TikTok Pixel and Hotjar in a GDPR form to your site.

License: Apache License 2.0

JavaScript 100.00%
analytics-tracking custom-cookie facebook-pixel gatsby-plugin google-analytics hotjar tiktok

gatsby-plugin-gdpr-cookies's People

Contributors

andrezimpel avatar brunoarueira avatar coldfire87 avatar dependabot[bot] avatar fbuireu avatar gabriardi avatar hahlh avatar nrandell avatar osvaldasvalutis avatar simonvanherweghe avatar sirdavidoflee avatar spaudanjo avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

gatsby-plugin-gdpr-cookies's Issues

Page views recording twice with GA4

I'm using version 1.0.12 with a Google Analytics 4 account, and the plugin seems to be working, except GA is recording all page views twice. This includes a first view fired by a call to initializeAndTrack following a cookie banner acceptance, and also through standard route changes. Only one visitor to the site is being recorded within the session, though.

My config looks like:

    {
      resolve: `gatsby-plugin-gdpr-cookies`,
      options: {
        googleAnalytics: {
          trackingId: 'G-6XXXXXXXXX',
          cookieName: 'siteMarketing',
          anonymize: true,
          allowAdFeatures: false,
        },
        googleTagManager: {
          trackingId: '',
          cookieName: 'siteMarketing',
          dataLayerName: 'dataLayer',
        },
        facebookPixel: {
          pixelId: '',
          cookieName: 'siteMarketing',
        },
      },
    }

What might be causing this issue?

Initialize as soon as user accepts consent

Thanks for your nice gatsby plugin! It is very convenient. But there is something that would make it even nicer:

Google Analytics is only activated when the user visits the page the second time. Until then ReactGA reports following warning in the console:
ReactGA.initialize must be called first or GoogleAnalytics should be loaded manually
Should the method ReactGA.initialize somehow be incorporated into onRouteUpdate?

Google Tag Manager firing Google Analytics fails

Hi,
I have installed everything as per documents for using Google Tag Manager. I have 2 tags set up, one for facebook pixel and the other for google analytics. When I test on tag assistant, both tags get fired on "Container Loaded" but firing status for google analytics is failed whereas facebook pixel shows succeeded.
Coudn't figure out the problem.
Appreciate help.
Thanks,

Issue #45 has not been merged back into v2.0

Hi, I have just tried to install and use this plugin with npm, but I believe it must be looking at the 2.0 branch because I had the error with GA passing options.trackingId despite the object being destructured in the method, as described and fixed in #45 and #46.

In the meantime I've just installed via npm i andrezimpel/gatsby-plugin-gdpr-cookies#master.

Thanks!

i see no difference before consent and after ..

so after adding the config below , and adding the cookie value true or false , nothing really change , i can see that gtm is always loaded in my network even without consent , datalayer is also available , and data are passed to my GTM .
i am using react-cookie-consent to set gatsby-gdpr-google-tagmanager true
what am i doing wrong? i doubled check my cookie name is the same as the one in my browser.

Thanks


    {
      resolve: `gatsby-plugin-gdpr-cookies`,
      options: {
        googleTagManager: {
          trackingId: process.env.GTM_PROPERTY, // leave empty if you want to disable the tracker
          cookieName: 'gatsby-gdpr-google-tagmanager', // // here can you change the cookie name
          dataLayerName: 'dataLayer', // default
        },
        environments: ['production', 'development'],
      },
    },

[Feature Request] Cookie names customization

First of all, thanks for this nice gatsby plugin! :)

I tried to use this plugin with react-cookie-consent to manage cookies, but hard-coded cookie names prevent an easy integration.

This fork shows how to expose cookie names in plugin configuration. With this feature you can also set a single cookie to manage both tracking services, ie. google analytics and facebook pixel.

Of course, I can send you a PR you can review before merge.

Warnings in console when using Google Analytics

I stumbled upon an issue with this plugin which causes warnings to be printed into the console.
This issue occurs once the user has given consent and the Google Analytics consent cookie has been set with a "true" value.
image
While this does not seem to break anything, it still isn't very nice.
Could this be fixed?

Using initializeAndTrack without @reach/router

Hello,

Is it possible to use initializeAndTrack without @reach/router? It is not compatible with react v17. Wondering if there's another third party library or built in Gatsby functionality I can use.

Thanks!

Support for Gatsby v4?

We're in the process of upgrading to v4 and noticed this plugin has hard dependencies in place:

npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! While resolving: [email protected]
npm ERR! Found: [email protected]
npm ERR! node_modules/gatsby
npm ERR!   gatsby@"^4.0.0" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer gatsby@"^2.24.77 || ^3.0.0" from [email protected]
npm ERR! node_modules/gatsby-plugin-gdpr-cookies
npm ERR!   gatsby-plugin-gdpr-cookies@"^2.0.6" from the root project

Is there any plans to update that?

G tag code commented out?

Thanks for this plugin. Made my life a lot easier.

I was looking at the GTAG code and I was wondering why the main methods were commented out. Is that on purpose or is it by mistake? It might be me that are misunderstanding how things works, but the other services seems to have the code active.

Best,
Anders

cant locate how to fix “gatsby-gdpr-google-analytics-legacy”

I noticed some bug on my cookie setting and noticed that my cookie name was gatsby-gdpr-google-analytics-legacy and trying to fix it in my codebase. I can‘t seem to locate it and need some pointers how to not use legacy. I hope this is related and I apologize if its not caused by gatsby-plugin-gdpr-cookies.

Thank you!

Screen Shot 2020-06-18 at 11 55 37

Events

Hi,

thanks for this great plugin! How can I use it to trigger events, such as with react-facebook-pixel?

ReactPixel.track( event, data ) 	
ReactPixel.trackCustom( event, data )

Thanks in advance!

GA user source always "Direct"

Hi,

I'm using this plugin with Google Analytics on my Gatsby-website. When a user entries the site for the first time the cookiebanner while be shown and the user have to choose whether he wants to accept or reject cookies. After the user selected one option the banner disapears and the page reloads (to call the onClientEntry hook) and there's my problem: Now I only see in Google Analytics, that the source of the user is "Direct" and not "Organic" or something else.

How can I fix this to get the "real source" of the users?

How to track outbound links

I am using gatsby-plugin-google-gtag. I opted for gatsby-plugin-gdpr-cookies so that google analytics only track when user gives permission but I was tracking outbound link with

import { OutboundLink } from "gatsby-plugin-google-gtag"

In closed issues a year someone said this plugin uses react-ga under the hood but it doesnt seem so.

How do I do that with gatsby-plugin-gdpr-cookies?

Thanks

Facebook pixelId not working

I've entered a Facebook pixel in the gatsby plugin settings (it's copied from Facebook, to ensure there are no typos).

I can't see the Facebook pixel code anywhere. I've tried both with production and development settings and only production.

In Facebook business manager I also get the notice that the pixel isn't active. The plugin simply doesn't seem to do anything with the pixelId.

After some digging around in the plugin. I extracted the code that should be the result of having the tracking Id present in the plugin, and run it directly in the onClientEntry in gatsby-browser.js in the plugin:

!function (f, b, e, v, n, t, s) {
    if (f.fbq) return;

    n = f.fbq = function () {
      n.callMethod ? n.callMethod.apply(n, arguments) : n.queue.push(arguments);
    };

    if (!f._fbq) f._fbq = n;
    n.push = n;
    n.loaded = !0;
    n.version = '2.0';
    n.queue = [];
    t = b.createElement(e);
    t.async = !0;
    t.src = v;
    s = b.getElementsByTagName(e)[0];
    s.parentNode.insertBefore(t, s);
  }(window, document, 'script', 'https://connect.facebook.net/en_US/fbevents.js');

  window.fbq("init", "[FACEBOOK_PIXEL_ID]");
  window.fbq("track", "PageView");

This works fine. Not really a permanent solution 😅 But works as a quick fix.
Something is definitely wrong in the Facebook pixel confirmation chain in the plugin. Let me know if I can help in some other way. I'll try and take another dive in the code in a couple of days if no one else has any suggestions 😄

EDIT
I'm tired and a was a little bit hasty... obviously this doesn't work when deploying remotely since plugins are installed on build. So This only works locally to see that there is something wrong with the Facebook pixel in the plugin.

Temporary fix

Putting the following in my gatsby-browser.js solves the issue for now.

exports.onClientEntry = () => {
	/* eslint-disable */

	!function (f, b, e, v, n, t, s) {
		if (f.fbq) return;

		n = f.fbq = function () {
			n.callMethod ? n.callMethod.apply(n, arguments) : n.queue.push(arguments);
		};

		if (!f._fbq) f._fbq = n;
		n.push = n;
		n.loaded = !0;
		n.version = '2.0';
		n.queue = [];
		t = b.createElement(e);
		t.async = !0;
		t.src = v;
		s = b.getElementsByTagName(e)[0];
		s.parentNode.insertBefore(t, s);
	}(window, document, 'script', 'https://connect.facebook.net/en_US/fbevents.js');
	/* eslint-enable */
	window.fbq("init", process.env.FACBOOK_PIXEL_ID);
	window.fbq("track", "PageView");
}

Versions

gatsby: 3.5.1,
gatsby-plugin-gdpr-cookies: 2.0.0,
react-cookie-consent: 6.2.4,

Environments-option has no effect

Hi, I am on version 2.0.0, and the environments-option in plugin config seems to have no effect.

I was running in development environment on my local machine, tested and tried out the plugin, and it seemed to work fine, so I removed the development -environment from the plugin config. But after restarting the process and a refresh, I still see that analytics and gtm is being loaded, on my browser network tab. I then also tried to remove even the production -environment from the config, but it has no effect. I have cookies with a consent present.

Is there a bug or am I missing something?

dataLayer doesn't update on route change

The dataLayer contents don't re-evaluate on route change, only on a full page reload.

To allow sending of consents through dataLayer reliably it needs to update dataLayer when the page changes.

routeChangeEvent not fired?

Hi,
II struggle to make google tag working for my site. I am using react-cookie-consent to set gatsby-gdpr-google-tagmanager true and this is working. However, it seems like routeChangeEvent is not fired as I don't see it in google tag assistant (Tag Manager Preview Mode). I have all the triggers in GTM set correctly - with official gatsby-plugin-google-tagmanager everything is working (except of course cookie consent).
Thank you in advance for your support.

Analytics not initializing after consent

I'm using react-cookie-consent to set 'gatsby-gdpr-google-analytics' to true. However, I've noticed that once its set to true, google analytics isn't initialized and doesn't begin tracking until a page refresh or a route change.

Any idea whats going on?

Google Analytics connection error

While inspecting the console I noticed that there seems to be an issue with google analytics. Not 100% sure this is from GRDP cookies plugin, but not sure what else it could be and wanted to see if anyone else has had similar issues?

Both browsers are latest version on latest macOS 11.3.1.

Chrome 90.0.4430.212
POST https://www.google-analytics.com/g/... net::ERR_CONNECTION_REFUSED

Safari 14.0.3
Beacon API cannot load https://www.google-analytics.com/g/...

Relevant Gatsby dependency versions
gatsby 3.5.x
gatsby-plugin-gdpr-cookies 2.0.0
react-cookie-consent 6.2.x

EDIT
Interestingly I've noticed similar analytics connection error on other sites as well. Might just be something on my end? Again, just wanted to make sure this isn't something others have encountered 🤓

Add Google Ads

First of all, Thank you for this great plugin. I just added it to my project and wanted to add Google Ads.

Can I just add it to the tracking Ids under google analytics. We don't use google tag manager atm.

How to capture outbound links?

Initially, I am using gatsby-plugin-google-analytics for the analytics setup. That library exposes a OutboundLink component to capture the outbound links. I think it makes sense to have something like that here too.

Thoughts?

[react-ga] ReactGA.initialize must be called first or GoogleAnalytics should be loaded manually

Hi guys,

I've installed your plugin and added my google analytics tracking id to the gatsby config.
But when I enter my website and set the cookie after I hit the accept button I receive this warning in the console:
[react-ga] ReactGA.initialize must be called first or GoogleAnalytics should be loaded manually
And unfortunately nothing is published to my Google Analytics Dashboard.
Am I missing something?

Is this problem maybe related to this issue: react-ga/react-ga#379?

support gatsby v3

hi there,

Just so it is noted, you might already be working on it, but the current version of this plugin is marked as incompatible with gatsby v3.
So supporting v3 would be great :).

Page Views firing twice

I'm using gatsby-plugin-gdpr-cookies with combination of gatsby-plugin-klaro

I'm using klaro strictly as cookie-consent-manger and triggering functions (linked below) onAccept or onReject. I also have event listeners on the button that trigger initializeAndTrack(location);
But I'm having this weird issue where google debugger is recording each route change as two page_views (see attached debugger console image), onEntry and once each page is clicked.

I'm not sure if I'm missing some configuration on gatsby-plugin-gdpr-cookies or if this is an actual bug.

Google Analytics Debugger Image
gatsby-plugin-gdpr-cookies
cookie functions

1.0.12 breaks with react 17.x

Works

...
"gatsby": "^2.29.3",
"gatsby-plugin-gdpr-cookies": "^1.0.11",
"react": "^17.0.1",
"react-dom": "^17.0.1",
...

While

...
"gatsby": "^2.29.3",
"gatsby-plugin-gdpr-cookies": "^1.0.12",
"react": "^17.0.1",
"react-dom": "^17.0.1",
...

produces the following error:

npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR! 
npm ERR! While resolving: [email protected]
npm ERR! Found: [email protected]
npm ERR! node_modules/react
npm ERR!   react@"^17.0.1" from the root project
npm ERR!   peer react@"^16.4.2 || ^17.0.0" from [email protected]
npm ERR!   node_modules/gatsby
npm ERR!     gatsby@"^2.29.3" from the root project
npm ERR!     peer gatsby@"^2.24.77" from [email protected]
npm ERR!     node_modules/gatsby-plugin-gdpr-cookies
npm ERR!       gatsby-plugin-gdpr-cookies@"^1.0.12" from the root project
npm ERR!   1 more (react-dom)
npm ERR! 
npm ERR! Could not resolve dependency:
npm ERR! peer react@"^16.13.1" from [email protected]
npm ERR! node_modules/gatsby-plugin-gdpr-cookies
npm ERR!   gatsby-plugin-gdpr-cookies@"^1.0.12" from the root project
npm ERR! 
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.

Any suggestions for a quick fix? Tried adding 17.x to peerDependencies, didn't help:

...
"peerDependencies": {
    "gatsby": "^2.24.77",
    "react": "^16.13.1 || ^17.x",
    "react-dom": "^16.13.1 || ^17.x"
  },
...

gaOptOut() is undefined

I've added the package to the gatsby site and added the google analytics ID as mentioned in the docs. I'm also setting a cookie with a value true/false based on user action. I would like to give an option to the user so that he can opt-out from future tracking.

I found the following in the docs section. <a href="javascript:gaOptout();">Deactivate Google Analytics</a> which can be used for opting out. I've used this and it doesn't seem working as expected. It throws an error saying that gaOptOut is undefined, which means that global analytics isn't set properly.

I might have missed something. How can I test if ga is being set properly?

Function to set the cookies to true

This plugin does not do anything to set the cookies to true, correct?

Why not expose some functions to do so? There is a cookie package, we know the cookie names. Could simply export some functions to do all the work, only have to call those functions from whatever button in the site.

An idea?

Remove console log

I appear to get a tracking analytics log in the console after installing this plugin. Can we turn this off through setting (eg disableLogOutput: true)?

LinkedIn tracking codes?

I have a use case for LinkedIn tracking. I'd be willing to submit a PR if it's something you would accept.

For now I'm just going to use this plugin as a template and add it directly into my Gatsby web project 😉

Facebook Pixel Support

Hi guys, been on a bit of a wild goose chase trying to get Facebook Pixel up and running, I'm probably doing something silly...

First up, I don't see a banner, initially I took it that I need to implement that myself and simply set gatsby-gdpr-facebook-pixel once the user accepts. So I decided to use react-cookie-consent and set this cookie on the onAccept event, works to a point but I need to refresh the page for the pixel to load so I tried to send a window.fbq("consent", "grant") but no luck.

So looking through the issues, I see that I should see a banner, I don't, but the further question would be, can I change the appearance of this banner? I can't see anything in the docs/code.
#4 (comment)

So if I was to use react-cookie-consent to implement the banner, how would I initialise the pixel on accept?

Hope that all makes sense.

Send hit directly after cookie consent

After the user hits the accept cookies button, how would I send the initial pageview to GA?
I understand your docs the way that only the next time on onRouteUpdate is called it would send a pageview?
(Or if the user again loads the page and onClientEntry is called)

Thanks

When the user hits declined the tracking continues

Hello,
I'm facing an issue when trying to implement the Decline function: the tracking continues whenever the user hits the "Decline" button (and it begins before the user accepts or declines).
Here's my Gatsby configuration:

    {
      resolve: `gatsby-plugin-gdpr-cookies`,
      options: {
        googleTagManager: {
          trackingId: 'UA-XXXXXX',
          cookieName: 'gatsby-gdpr-google-tagmanager',
          defaultDataLayer: { platform: 'gatsby' },
        },
        facebookPixel: {
          pixelId: 'XXXXXXXXXXXX',
          cookieName: 'gatsby-gdpr-facebook-pixel',
        },
        environments: ['production'],
      },
    },

and in my Layout.js component:

import CookieConsent, { Cookies } from 'react-cookie-consent';
import { useLocation } from '@gatsbyjs/reach-router'; // this helps tracking the location
import { initializeAndTrack } from 'gatsby-plugin-gdpr-cookies';

export default function Layout({ children }) {
  const location = useLocation();
  const slug = location.pathname.replace(/[\/\\]/g, '');

  return (
    <div>
      <LayoutStyles>
        <Header />
        <div className="content">
          {children}
        </div>
        <Footer footerItems={footerItems} />
        <CookieConsent
          location="bottom"
          buttonText="J'accepte"
          declineButtonText="Je refuse"
          cookieName="gatsby-gdpr-google-tagmanager"
          expires={150}
          onAccept={() => {
            Cookies.set('gatsby-gdpr-google-tagmanager', true);
            Cookies.set('gatsby-gdpr-facebook-pixel', true);
            initializeAndTrack(location);
          }}
          enableDeclineButton
          onDecline={() => {
            Cookies.set('gatsby-gdpr-google-tagmanager', false);
            Cookies.set('gatsby-gdpr-facebook-pixel', false);
          }}
        >
          En continuant à utiliser le site, vous acceptez l’utilisation de
          cookies.
        </CookieConsent>
      </LayoutStyles>
    </div>
  );
}

I don't know what I'm doing wrong here.

Thanks for any help on this!

GTM is tracking without permission

This package is building tag manager in gatsby-ssr.js, so when I enter my website the tag manager is already working, but that's not what I want, I need that user accept cookies first, then start tag manager.

A solution is:

use react-gtm-module (like react-ga) to initialize it.

so in onClientEntry you can add:

    // google tagmanager
    if (
      cookies.get(options.googleTagManager.cookieName) === `true` &&
      validGTMTrackingId(options)
    ) {
      ReactGTM.initialize({ gtmId: options.googleTagManager.trackingId })
    }

PS: I can't do this PR now, I'm out of time :(

Cross-domain Measurement

Hey,

I'm using the plugin on a headless Shopify website and I need to set up cross-domain tracking so all of our analytics match up once the user goes from the customdomain.com to the checkout page which is hosted on customdomain.myshopify.com.

According to the docs this is possible by adding in the linker:autoLink code as outlined in the linked example.

I couldn't see a way to do this with the existing plugin options, but I might just be missing something.

Any help would be greatly appreciated.

Thanks!

Pagespeed insights/ Core vitals issue

Great work on the plugin, I use it on all my sites.

I am working on my page speed due to the upcoming changes in google algorythm and I have run into a problem.
"Remove unused JavaScript to reduce bytes consumed by network activity. "
I guess we don't really need to load this script until the user has consented right?

image

Is there ability to add other tracking services?

We have added this plugin to our Gatsby site and currently it seems to work great. However, other sites we have worked on use different types of tracking systems along with GTM. Is there, or could there be added, a way to include other scripts to the process besides the 3 you have currently? Maybe a way to add a custom or pre-defined script to the optional loader as well?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.