Setup instructions for Google Analytics 4

Google has recently released Google Analytics 4, Below are few suggestions for Discourse:

  1. Add gtag.js directly to your pages: Add option in Dashboard to add Google Analytics 4 gtag.js directly (Yes, this can be done by embedding gtag directly in head, but for discourse additional configuration may be required). While this may take some time for development, second option can work for most meanwhile
  2. Add your Tag using Google Tag Manager: Update existing guide at Setup Google Tag Manager for Analytics for Google Analytics 4
  3. Add gtag.js directly to your web pages that are already - tagged with analytics.js: while this is an option currently, but Universal Analytics will be phased out over a period of time
4 Likes

We have this on our radar to implement and phase out analytics.js to gtag.js. We’ll update this topic when the update is ready to go.

8 Likes

We just merged an option to upgrade to GA v4 into core:

https://github.com/discourse/discourse/commit/09b8a61f65e5a07e4fdec90ff996396b4512a40e

To upgrade to Universal Analytics v4 which uses gtag as a wrapper for analytics.js, head to Admin > Settings and search for ga_version. Switch this setting to v4_gtag and refresh to upgrade to version 4.

Be aware in upgrading to v4 you will need to change any custom events you’ve defined in theme components to use the new gtag API instead of ga.

9 Likes

Do we need to change the ga universal tracking code to this new App + Web Id too or just leave it with the old UA-xxxxxxx-x id number?

1 Like

Setup 1

image

Result 1

image

Setup 2

Result 2 - OK

image

1 Like

Thanks. Now I got it working. :sunglasses:

The only con so far is not having the historical data from the universal tracker on the new GA4. :triumph:

2 Likes

Thank you, works well!

How can I set the following options to make tracking GDPR-compliant (w/o consent that is):

    gtag("config", "XYZ", {
      anonymize_ip: true,
      client_storage: "none",
    });

You should be able to add that code in via a theme component, but I haven’t tested it.

Using v4_gtag and entering G-XXXXXXXXXX is resulting into multiple page views for single page visit.

Also is there any way to avoid inserting analytics code in admin section?

It’s possible to send data into both UA and GA4. That way there is historical data for comparison after the UA data is deleted next year.

I put the UA-gtag.js code snippet in <head> and added one more line to send data into GA4:

gtag('config', 'UA-********-**', { "anonymize_ip": true });
gtag('config', 'G-*********', { "anonymize_ip": true );

Does anyone know what additional configuration might be required? It seems to be working here, but my GA configuration is simple.

3 Likes