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.

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

7 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?

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?