DavidWells / analytics

Lightweight analytics abstraction layer for tracking page views, custom events, & identifying visitors
https://getanalytics.io
MIT License
2.43k stars 247 forks source link

Google Consent Mode v2 #425

Closed alissonpadua closed 7 months ago

alissonpadua commented 7 months ago

Hello all!

Is there anyone working on the implementation Google Consent Mode v2 already ? I'm asking because it will be mandatory in the EU and I would like to followup and help on that if it's possible.

DavidWells commented 7 months ago

Not sure if anyone is working on updates for this. (I will not have bandwidth for this personally)

The good news is, nothing in analytics loads until analytics lib is initialized. So you can do whatever consent things you might need before you create an analytics instance with your plugins.

OR you can start analytics and disable all calls like so https://getanalytics.io/conditional-loading/#disabling-initial-loading. This won't stop underlying libs from doing other things though like setting cookies etc. So you might want to go with the first option.

It appears like consent mode are just some additional gtag calls https://developers.google.com/tag-platform/security/guides/consent?consentmode=advanced You can extend the base google-analytics plugin with methods to add this functionality.

Example:

import Analytics from "analytics";
import googleAnalytics from "@analytics/google-analytics";

// Original GA
const originalPlugin = googleAnalytics({
  trackingId: "UA-1234567",
});
// Customized GA until option added
const enhancedGAPlugin = Object.assign({}, originalPlugin, {
  // add custom methods
  methods: {
    ...(originalPlugin.methods || {}),
    ...{
      consent: () => {
        if (typeof gtag !== "undefined") {
          gtag("consent", "update", {
            ad_user_data: "granted",
            ad_personalization: "granted",
            ad_storage: "granted",
            analytics_storage: "granted",
          });
        }
      },
    },
  },
});

/* initialize analytics and load plugins */
const analytics = Analytics({
  app: "cool-apps",
  plugins: [enhancedGAPlugin],
});

// Then you can call custom methods like so
// analytics.plugins['plugin name'].methodName()
analytics.plugins["google-analytics"].consent();
alissonpadua commented 7 months ago

Perfect explanation @DavidWells thank you.

DavidWells commented 7 months ago

Hey no problem.

would love to see the code if you implement this on your end.

closing this issue for now