codler / react-ga4

React Google Analytics 4
https://www.npmjs.com/package/react-ga4
266 stars 34 forks source link

How to set and update consent mode according to google official docs on CMP with react-ga4? #57

Open Andrea-Dispe opened 11 months ago

Andrea-Dispe commented 11 months ago

Not a real issue but I am trying to figure out how to set and update google CMP (Consent Management Platform) with react-ga4. According to the official google doc official google doc on consent mode this script:

gtag('consent', 'default', {
  'ad_storage': 'denied',
  'analytics_storage': 'denied'
}); 

will be added to the head and then the consent mode banner will have to update it with this:

gtag('consent', 'update', {
  'ad_storage': 'granted'
});

How to achieve this just by using react-ga4?

ReyasHey commented 10 months ago

I started using the library recently and ran into the same roadblock

I'm assuming these settings would go in the "gtagOptions" when initializing at least

ReactGA.initialize([
  {
    trackingId: "your GA measurement id",
    gtagOptions: {...}, // <-----
  }
]);

Sadly fiddling with its "any" type doesn't sound very appealing to me

So I've resorted to manually removing the cookies on consent denied by the user kinda like this article from dev.to says As well as initializing without an ID when consent is denied, then initializing correctly when consent is granted

Would be awesome if this could be done directly with the library or is on the roadmap!

ouroboroscoding commented 8 months ago

@ReyasHey that example doesn't really accomplish the goal though, it's a very strict on or off. My understanding of the google consent policy is we can still use analytics even if the user denies access, it's just that google will not store cookies, and will strip out all the user identifying information. We really need a way to enable/disable this in react-ga4 without having to completely turn off analytics.

PaloSP commented 8 months ago

I think we can use this before initialization:

 ReactGA.gtag("consent", "default", {
    ad_storage: "denied",
    ad_user_data: "denied",
    ad_personalization: "denied",
    analytics_storage: "denied",
  });

and later

 ReactGA.gtag("consent", "update", {
      analytics_storage: "granted",
    });
ouroboroscoding commented 8 months ago

@PaloSP that worked, thanks for the info!