react-ga4 icon indicating copy to clipboard operation
react-ga4 copied to clipboard

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

Open Andrea-Dispe opened this issue 2 years ago • 4 comments

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?

Andrea-Dispe avatar Oct 16 '23 08:10 Andrea-Dispe

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!

ReyasHey avatar Nov 11 '23 22:11 ReyasHey

@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.

ouroboroscoding avatar Jan 10 '24 20:01 ouroboroscoding

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",
    });

PaloSP avatar Jan 27 '24 11:01 PaloSP

@PaloSP that worked, thanks for the info!

ouroboroscoding avatar Feb 01 '24 17:02 ouroboroscoding