Documentation / Product / Integrations / Google / Google Marketing

Google Analytics 4 (GA4)

GA4, which was first released into beta in 2019, has replaced Universal Analytics (UA) as the default version for Google Analytics installations. GA4 offers a great deal of flexibility and power over its predecessor. The following document outlines the preferred method for enriching GA4 with an individual's profile information, such as audience membership and Lytics user ID.

There are a variety of robust use cases enabled by this integration, most notably the ability to filter GA4 dashboards by Lytics Audiences as well as distribute those audiences efficiently across the Google ecosystem from GA4 directly. Lastly, web properties are complicated by nature. The following recommended approach aims to focus on ease of installation while also preventing a limitation of the power of GA4. Please note that it is always recommended that you consult with your technical teams or partners before proceeding.

Integration Details

If leveraging the workflow to configure new Dimensions on your behalf, this integration will use the Google Analytics Universal Analytics API. Alternatively, custom user scoped dimensions can be configured manually. Passing the audience membership data or IDs will leverage the profile request API within our JavaScript tag along with the GA4 set user_properties API.

Step 1: Creating Dimensions

To attribute onsite events such as page views or purchases, you must first define new Custom User Scoped Dimensions to store the set of audiences and/or User ID depending on preference. This can be done through our server-to-server integration, in which we'll create two properties: Lytics User ID (ly_user_id_dim) and Lytics Audiences (ly_segments_dim). Alternatively, because we'll pass the data to Google via JavaScript, you can create whatever dimensions you want by following Google's documentation. If taking the manual approach, just be sure to use the user scope option during creation. For details on our server-to-server integration please view our Google Analytics: Setup Custom Dimensions instructions. GA4 Dimensions

Step 2: Enabling Lytics Audiences

Once the necessary dimensions exist within your preferred Google Analytics account, you'll need to ensure all audiences you would like to send to GA4 are flagged as API Enabled from the Audience edit area of Lytics. This feature ensures no data is ever shared or passed to another tool without your explicit instructions to do so.

Step 3: Configuring GA4

Finally, leveraging the profile listener feature of our JavaScript tag, we'll get details of the current visitor and pass those along to GA4 via your new dimensions. Since there are a nearly infinite number of ways sites can be configured and constructed, it is always best to consult your technical team on this step. Here we'll outline the most common approach assuming that GA4 tag installation default instructions were followed.

Installing GA4

A typical installation of GA4 is completed by installing a few lines of JavaScript on your site. Typically in the header or footer.

<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-D2LPRHX5G4"></script>
<script>
    window.dataLayer = window.dataLayer || [];
    function gtag(){dataLayer.push(arguments);}
    gtag('js', new Date());

    gtag('config', 'YOUR-PROPERTY-ID');
</script>

Setting User Properties

This will need to be also modified to include the setting of your custom dimensions as well as optionally altering how the initial pageview event is fired. The following example shows ultimately how we'll be sending data to GA4.

gtag('set', 'user_properties', {
    'ly_segments_dim': 'one,two,three',
    'ly_user_id_dim': 'myid123'
});

Getting Profile Data

To pass the current user's audience information as well as optional user ID, you'll first need to retrieve the profile via our personalization API. Luckily the Lytics tag makes this simple using our entityready listener. The Lytics tag will call the desired function once it has identified the user and accessed their profile. Using the information returned, we'll send the user properties as outlined above.

<script type="text/javascript">
  var myCallbackFunction = function(profile){
      // do something here with the profile
      console.log(profile.data.user.segments);
  }

  jstag.call('entityReady', myCallbackFunction); // register the listener
</script>

Full Example

We'll alter the default listener example to verify we did receive audience membership data and then pass that along to GA4 as our lytics_segments_dim dimensions or whatever you named it during the manual creation process.

<!-- Start Send Lytics Audiences to GA4 -->
<script type="text/javascript">
    var handleGA4UserProperties = function(profile){
        if (window.gtag) {
            // ensure we have segments to send to prevent javascript errors
            if(typeof profile != "undefined" && typeof profile.data != "undefined" && typeof profile.data.user != "undefined" && typeof profile.data.user.segments != "undefined") {
                // send the audience membership to GA4 as a user property
                gtag('set', 'user_properties', {
                    'ly_segments_dim': profile.data.user.segments.join(',')
                });
            };
        } else {
            // log a warning if the profile can't be accessed
            console.warn('unable to set audience membership in GA4');
        }
    }

    jstag.call('entityReady', handleGA4UserProperties); // register the entityReady listener
</script>
<!-- End Send Lytics Audiences to GA4 -->

In this case, we also log a warning to the console when a set of audience memberships are unavailable for debugging purposes. For demonstration purposes, a full HTML example of loading the GA4 tag, Lytics tag, and listener function might look like the following:

<html>
    <head>
        <!-- Global site tag (gtag.js) - Google Analytics -->
        <script async src="https://www.googletagmanager.com/gtag/js?id=G-D2LPRHX5G4"></script>
        <script>
            window.dataLayer = window.dataLayer || [];
            function gtag(){dataLayer.push(arguments);}
            gtag('js', new Date());

            gtag('config', 'YOUR-GA4-PROPERTY-ID');
        </script>
    </head>
    <body>
        Lytics GA4 Demonstration

        <!-- Start Lytics Tracking Tag Version 3 -->
        <script type="text/javascript">
            !function(){"use strict";var o=window.jstag||(window.jstag={}),r=[];function n(e){o[e]=function(){for(var n=arguments.length,t=new Array(n),i=0;i<n;i++)t[i]=arguments[i];r.push([e,t])}}n("send"),n("mock"),n("identify"),n("pageView"),n("unblock"),n("getid"),n("setid"),n("loadEntity"),n("getEntity"),n("on"),n("once"),n("call"),o.loadScript=function(n,t,i){var e=document.createElement("script");e.async=!0,e.src=n,e.onload=t,e.onerror=i;var o=document.getElementsByTagName("script")[0],r=o&&o.parentNode||document.head||document.body,c=o||r.lastChild;return null!=c?r.insertBefore(e,c):r.appendChild(e),this},o.init=function n(t){return this.config=t,this.loadScript(t.src,function(){if(o.init===n)throw new Error("Load error!");o.init(o.config),function(){for(var n=0;n<r.length;n++){var t=r[n][0],i=r[n][1];o[t].apply(o,i)}r=void 0}()}),this}}();
            // Define config and initialize Lytics tracking tag.
            // - The setup below will disable the automatic sending of Page Analysis Information (to prevent duplicative sends, as this same information will be included in the jstag.pageView() call below, by default)
            jstag.init({
            src: 'https://c.lytics.io/api/tag/YOUR-LYTICS-ACCOUNT-ID/latest.min.js',
            pageAnalysis: {
                dataLayerPull: {
                disabled: true
                }
            }
            });

            // You may need to send a page view, depending on your use-case
            jstag.pageView();
        </script>

        <script type="text/javascript">
            var handleGA4UserProperties = function(profile){
                if (window.gtag) {
                    // ensure we have segments to send to prevent javascript errors
                    if(typeof profile != "undefined" && typeof profile.data != "undefined" && typeof profile.data.user != "undefined" && typeof profile.data.user.segments != "undefined") {
                        // send the audience membership to GA4 as a user property
                        gtag('set', 'user_properties', {
                            'ly_segments_dim': profile.data.user.segments.join(',')
                        });
                    };
                } else {
                    // log a warning if the profile can't be accessed
                    console.warn('unable to set audience membership in GA4');
                }
            }

            jstag.call('entityReady', handleGA4UserProperties); // register the entityReady listener
        </script>
    </body>
</html>

Additional Considerations

At this point, you should successfully pass audience membership to GA4 for each user. Given the flexibility of GA4, there are a variety of configuration options. That said, there are a couple of common points that are worth considering.

  1. The load order of tags is essential. For this to work correctly, you'll want to load tags in this order:
    1. GA4
    2. Lytics Tag
    3. Lytics Listener
  2. It may be desired that the GA4 default pageView tag is delayed until the profile information has been set. This ensures all events are associated with the user but could impact the efficiency of tracking page views. This is only recommended for advanced users with a firm understanding of JavaScript. In this case, you would disable the default page view as described here and then fire it manually following the setting of the user properties in our example.
  3. It may be desired to send an event to GA4 noting when the properties are set. This can be done following the entityready function and the user properties being set. For more information on the various ways to configure events, consult Google's documentation.
  4. When testing your integration, Google supports a debug setting in their tag configuration settings. These settings allow access to a debug view where you can see the events stream in real-time to confirm proper behavior.

Step 4: Add GA4 Audience

The final step of this integration is to follow Google's recommended approach for building an audience inside of GA4 using custom dimensions. When prompted which dimension to use, you'll want to select the ly_segments_dim or whatever custom parameter you created and then match based on the value of your audience or a regex match. When passing the audiences to GA4, Lytics converts them to a string separated by commas as Google does not accept arrays. As such, the dimension value will look similar to audience1,audience2,audience3. GA4 Audience Creation