HomeGuidesAPI Reference
Submit Documentation FeedbackJoin Developer CommunityOptimizely GitHubOptimizely NuGetLog In

Configure GA4 using GTM

Use Google Analytics 4 (GA4) to capture and analyze traffic data across your websites and applications.

πŸ“˜

GA4 is replacing Google Universal Analytics (UA)

Starting July 1, 2023, GA4 will replace standard Google Universal Analytics (UA), which will no longer process data. For more information, see Introducing Google Analytics 4 (GA4).

πŸ“˜

Note

This articles describes a custom GA4 integration option. We are working on building the GA4 integration option into Optimizely Web Experimentation (similar to the Google Universal Analytics integration).

If you use Google Analytics to monitor your project’s traffic, you can view the results of your Optimizely experiments alongside the rest of the data that Google Analytics collects.

You can set up the integration between Optimizely Web Experimentation and Google Analytics 4 (GA4) both with and without Google Tag Manager (GTM). This article covers setting up the integration using GTM. For instructions on setting up the GA4 integration without using GTM, see this article.

Configure GA4 in Optimizely Web

Step 1. Add script in GTM

In GTM, add the following script as a custom HTML tag using the steps below. This script should run on every page:

  1. Go to Workspace > Tags > New.
  1. Enter Optimizely integration code in the Untitled Variable field.
  1. Click Tag Configuration and select Custom HTML.
  1. Copy the code below and paste it into the HTML field.

πŸ“˜

Note

If you want to send campaignData as well, you can add it to the sendCampaignData function in the script. This is also where you can adjust the dataLayer.push to any naming convention you prefer.

<script>
var DATALAYER_OBJECT_NAME = 'dataLayer';
/**
* Some analytics platforms have the ability to fix referrer values by overriding the page referrer value.
* this function is called when a redirect has occurred on the previous page.
*
* @param {string} referrer - The effective referrer value
*/
var referrerOverride = function(referrer) {
    var dataLayerObject = window[DATALAYER_OBJECT_NAME] || [];
    dataLayerObject.push({
      'event': 'optimizely-referrer-override',
      'optimizely-referrer': referrer
    });
};

/**
* Used for experiments created in Optimizely. This function is executed for all
* experiments that are running on the page. Use the arguments to send data to your platform.
*
* @param {string} campaignId - The ID of a campaign that is running on the page
* @param {string} integrationString - Integration string for a particular campaign
*   which is a sample of the visitor that isn't exposed so that Optimizely can calculate the impact of a campaign.
*/

var sendCampaignData = function(campaignId, integrationString) {
    var dataLayerObject = window[DATALAYER_OBJECT_NAME] || [];
    dataLayerObject.push({
        'event': 'optimizely_decision_web',
        'optimizely_experiment': integrationString.experiment,
        'optimizely_variant': integrationString.variation
    });
};

/**
* This function fetches the campaign integration string from the Optimizely client
* and calls the functions provided in the arguments with the data that needs to
* be used for sending information. It is recommended to leave this function as is
* and to create your own implementation of the functions referrerOverride and
* sendCampaignData.
*
* @param {Function} referrerOverride - This function is called if the effective referrer value differs from
*   the current document.referrer value. The only argument provided is the effective referrer value.
* @param {Function} sendCampaignData - This function is called for every running campaign on the page.
*   The function is called with all the relevant ids and names.
*/
var initNewOptimizelyIntegration = function(referrerOverride, sendCampaignData) {
  // There can only be one effective referrer on a page. This boolean makes sure the
  // redirect overwrite only happens once. Multiple referrerOverwrites might result in undesired behavior.
  var referrerOverwritten = false;
  var newActiveCampaign = function(id) {
    var state = window['optimizely'].get && window['optimizely'].get('state');
    var referrer = state.getRedirectInfo() && state.getRedirectInfo().referrer;
    if (!referrerOverwritten && referrer) {
      referrerOverride(referrer);
      referrerOverwritten = true;
    }

    var campaignId = id;
    var integrationString = state.getDecisionObject({'campaignId':campaignId});

    sendCampaignData(campaignId, integrationString);
  };

  /**
   * At any moment, a new campaign can be activated (manual or conditional activation).
   * This function registers a listener that listens to newly activated campaigns and
   * handles them.
   */
  var registerFutureActiveCampaigns = function() {
    window.optimizely = window.optimizely || [];
    try{
      window.optimizely.push({
        type: 'addListener',
        filter: {
          type: 'lifecycle',
          name: 'campaignDecided'
        },
        handler: function(event) {
          var id = event.data.campaign.id;
          newActiveCampaign(id);
        }
      });
    }catch(error){
      console.log('Something went wrong, this error can occur if there is a client side SDK. Which overwrites the optimizely object.');
    }
  };

  /**
   * If this code is running after Optimizely on the page, there might already be
   * some campaigns active. This function makes sure all those campaigns are
   * handled.
   */
  var registerCurrentlyActiveCampaigns = function(){
    var state = window['optimizely'] && window['optimizely'].get && window['optimizely'].get('state');
    if (state) {
      var activeCampaigns = state.getCampaignStates({
        isActive: true
      });
      for (var id in activeCampaigns) {
        newActiveCampaign(id);
      }
    }
  };

  registerCurrentlyActiveCampaigns();
  registerFutureActiveCampaigns();
};

/**
* A wrapper around the logic for the new Optimizely integration.
* @param {Function} referrerOverride - This function is called if the effective referrer value differs from
*   the current document.referrer value. The only argument provided is the effective referrer value.
* @param {Function} sendCampaignData - This function is called for every running campaign on the page.
*   The function is called with all the relevant ids and names.
*/
var initOptimizelyIntegration = function(referrerOverride, sendCampaignData) {
  initNewOptimizelyIntegration(referrerOverride, sendCampaignData);
};

initOptimizelyIntegration(referrerOverride, sendCampaignData);

</script>
  1. Click Triggering and select All Pages.
  1. Click Save.

Step 2. Add User-Defined Variables in GTM

In GTM, complete the following steps to add the optimizely_experiment and optimizely_variant variables:

  1. Go to Workspace > Variables > New.
  1. Enter optimizely_experiment in the Untitled Variable field.
  1. Click Variable Configuration and select Data Layer Variable.
  1. In the Data Layer Variable Name field, enter optimizely_experiment.
  1. Click Save.
  2. Repeat step 1 through step 6 for the optimizely_variant variable.

Step 3. Set up the configuration tag in GTM

In GTM, complete the following steps to set up a Google Analytics GA4 Configuration tag:

  1. Go to Workspace > Tags > New.
  1. Enter Google Analytics GA4 Configuration in the Untitled Tag field.
  1. Click Tag Configuration and select Google Analytics: GA4 Configuration.
  1. Enter your Measurement ID.
  1. Click Triggering and select Initialization - All Pages.
  1. Click Save.

Step 4. Set up the event tag in GTM

In GTM, complete the following steps to set up an Optimizely X - GA4 event tag:

  1. Go to Workspace > Tags > New.
  1. Enter Optimizely X - GA4 event in the Untitled Tag field.
  1. Click Tag Configuration and select Google Analytics: GA4 Event.
  1. Expand the Configuration Tag drop-down list and select Google Analytics GA4 Configuration.
  1. In the Event Name field, enter optimizely_decision_web.

πŸ“˜

Note

If you plan to integrate Optimizely Full Stack with GA4 as well, enter optimizely_decision_web to distinguish the event names between both the Optimizely Web and Optimizely Full Stack GA4 integrations. Otherwise, enter optimizely_decision.

  1. Expand Event Parameters and then click Add Row.
  2. In the Parameter Name field, enter optimizely_experiment.
  1. In the Value field, click the value select icon and then select optimizely_experiment.
  2. Click Add Row again.
  3. In the Parameter Name field, enter optimizely_variant.
  1. In the Value field, click the value select icon and then select optimizely_variant.
  2. Click Triggering and then click the New Trigger icon to create the following trigger:
    1. Enter Optimizely X - GA4 event trigger in the Untitled Trigger field.
2. Click **Trigger Configuration** and select **Custom Event**.
   
3. In the **Event name** field, enter `optimizely_decision_web`.
   
4. Click **Save **and then click **Save **again on the overall tag setup page.
   
  1. Now submit and publish your workspace changes by going to Workspace >Β  Submit > Publish (adding any details you would like to the Submission Configuration).