Use Google Analytics 4 (GA4) to capture and analyze traffic data across your websites and applications.
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.
Table of Contents
- Step 1. Add script in GTM
- Step 2. Add User-Defined Variables in GTM
- Step 3. Set up the configuration tag in GTM
- Step 4. Set up the event tag in GTM
Set up GA4 in Optimizely Web Experimentation
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:
- Go to Workspace > Tags > New.
- Enter Optimizely integration code in the Untitled Variable field.
- Click Tag Configuration and select Custom HTML.
- Copy the code below and paste it into the HTML field.
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',
'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> - Click Triggering and select All Pages.
- 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:
- Go to Workspace > Variables > New.
- Enter optimizely-experiment in the Untitled Variable field.
- Click Variable Configuration and select Data Layer Variable.
- In the Data Layer Variable Name field, enter optimizely-experiment.
- Click Save.
- 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:
- Go to Workspace > Tags > New.
- Enter Google Analytics GA4 Configuration in the Untitled Tag field
- Click Tag Configuration and select Google Analytics: GA4 Configuration.
- Enter your Measurement ID.
- Click Triggering and select Initialization - All Pages.
- 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:
- Go to Workspace > Tags > New.
- Enter Optimizely X - GA4 event in the Untitled Tag field.
- Click Tag Configuration and select Google Analytics: GA4 Event.
- Expand the Configuration Tag drop-down list and select Google Analytics GA4 Configuration.
- In the Event Name field, enter optimizely-decision.
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.
- Click Event Parameters and then click Add Row.
- In the Parameter Name field, enter optimizely-experiment.
- In the Value field, click the value select icon and then select optimizely-experiment.
- Click Add Row again.
- In the Parameter Name field, enter optimizely-variant.
- In the Value field, click the value select icon and then select optimizely-variant.
- Click Triggering and then click the New Trigger icon to create the following trigger:
- Enter Optimizely X - GA4 event trigger in the Untitled Trigger field.
- Click Trigger Configuration and select Custom Event.
- In the Event name field, enter optimizely-decision.
- Click Save and then click Save again on the overall tag setup page.
- Enter Optimizely X - GA4 event trigger in the Untitled Trigger field.
- Now submit and publish your workspace changes by going to Workspace > Submit > Publish (adding any details you would like to the Submission Configuration).