How to tag for both Universal Analytics and Google Analytics 4 properties

This article describes how to instrument a website/web-app with tags to populate Universal Analytics (UA) and Google Analytics 4 (GA4) properties at the same time. More advanced functionality (e.g. ecommerce) is covered in companion articles.

Use the following buttons to pick the library you are currently using:

Set up the basic page tag

To populate both your UA and GA4 properties, you’ll need to either add a new tag or modify your existing page tag.

If you already use gtag.js for your UA property, you can either

  • add one line to your existing gtag.js page snippet as explained below, or
  • use Connected Site Tags to add your GA4 Measurement ID without changing the code on your page.

To change your code, add the following config command to your existing gtag.js snippet:

gtag('config', 'G-XXXXXXXXXX');

where G-XXXXXXXXXX is the Measurement ID for a GA4 data stream.

For example, here is the complete gtag.js snippet you would use to collect data for a UA property with an ID of 'UA-XXXXXX-13' and a GA4 data stream ID of 'G-XXXXXXXXXX'.

<script async src="https://www.googletagmanager.com/gtag/js?id=UA-XXXXXX-13"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'UA-XXXXXX-13');
  gtag('config', 'G-XXXXXXXXXX');
</script>

Generate a virtual pageview

If you generate virtual pageviews in analytics.js, for example:

ga('set', 'page', '/my-virtualpage-path');
ga('send', 'pageview');

you can do the same thing in gtag.js as follows:

gtag('config', 'G-XXXXXXXXXX', {
  'page_path': '/my-virtualpage-path'
});

Modify your existing gtag.js code to also generate a virtual pageview in your GA4 property. The following gtag.js code generates a virtual page view in both a UA and an GA4 property.

<script>
  gtag('config', 'UA-XXXXXX-13', {
  'page_title' : 'my-virtualpage-title',
  'page_path': '/my-virtualpage-path'
  });
  gtag('config', 'G-XXXXXXXXXX', {
  'page_title' : 'my-virtualpage-title',
  'page_path': '/my-virtualpage-path'
  });
</script>

Disable data collection

If your site's privacy policy provides an option for the user to opt-out of Google Analytics, you’ll need to instrument the opt-out for both your UA and GA4 properties.

Add the additional line of code to your existing gtag.js snippet.

window['ga-disable-G-XXXXXXXXXX'] = true;

where G-XXXXXXXXXX is the Measurement ID for your GA4 data stream.

IP anonymization

In GA4 properties, IP addresses are automatically anonymized.

Cross-domain Measurement

In GA4 properties, cross-domain measurement configuration is handled entirely from the Google Analytics user interface. See Measure activity across domains.