A/B testing is a cornerstone of optimizing digital experiences. Whether you’re testing landing page designs, call-to-action buttons, or content layouts, a well-structured A/B test can significantly impact conversion rates. In this blog post, we’ll walk you through how to set up an A/B testing script using Google Tag Manager (GTM) and send the results to Google Analytics 4 (GA4) for analysis.
By the end of this guide, you’ll have a ready-to-use script that:
- Randomly assigns users to one of two versions (A or B).
- Redirects users to the corresponding page based on their assignment.
- Tracks experiment participants and their group in GA4.
Why Use GTM and GA4 for A/B Testing?
Google Tag Manager simplifies deploying scripts on your website without needing direct access to the codebase. With GA4’s advanced analytics capabilities, you can measure the performance of your A/B test and gain actionable insights, such as how users interact with each version.
In our case is a very important tool to allow the QA team adjust the experiment probability and change the percentage of users going to each version.
The Script: Setting Up A/B Testing in GTM
Here’s the complete JavaScript code you’ll use in GTM:
(function() { // Define the percentage of users entering the experiment (0 to 100) var experimentPercentage = 50; // Example: 50% of users enter the experiment // Define the probability of assigning users to version B (0 to 1) var bVersionProbability = 0.5; // Example: 50% of experiment users go to version B // Define the URLs for the A and B versions var urlA = "https://example.com/version-a"; var urlB = "https://example.com/version-b"; // Helper function to determine if a user enters the experiment function isInExperiment() { return Math.random() < experimentPercentage / 100; } // Retrieve the stored variant from localStorage to maintain consistency var variant = localStorage.getItem('abTestVariant'); // If no variant is stored and the user enters the experiment, assign one if (!variant) { if (isInExperiment()) { variant = Math.random() < bVersionProbability ? 'B' : 'A'; localStorage.setItem('abTestVariant', variant); // Send an event to GA4 for entering the experiment sendGA4Event("experiment_entered", { experiment_group: variant }); } else { variant = 'Control'; // Not in the experiment localStorage.setItem('abTestVariant', variant); } } // Redirect users based on the assigned variant if (variant === 'A' && window.location.href !== urlA) { window.location.href = urlA; } else if (variant === 'B' && window.location.href !== urlB) { window.location.href = urlB; } // Send an event to Google Analytics 4 for the user's variant assignment sendGA4Event("ab_test_assignment", { ab_test_variant: variant }); // Function to push an event to the GA4 Data Layer function sendGA4Event(eventName, params) { window.dataLayer = window.dataLayer || []; window.dataLayer.push({ event: eventName, ...params }); }})();
Customizable Experiment Settings:
- Control the percentage of users who enter the experiment (experimentPercentage).
- Set the probability of users being assigned to version B (bVersionProbability).
Consistent User Experience:
- Once assigned to a group, users stay in the same group throughout their session using localStorage.
Google Analytics 4 Integration:
- Tracks the experiment participation (experiment_entered) and the variant assignment (ab_test_assignment).
How to Implement the Script in Google Tag Manager
Follow these steps to deploy the script:
Step 1: Create a Custom HTML Tag
- Open GTM and go to Tags > New > Custom HTML.
- Paste the script into the editor.
- Name the tag (e.g., “A/B Test Redirect and Tracking”).
Step 2: Add a Trigger
- Assign a Page View trigger to the tag so it fires on all page views.
- Save the tag.
Step 3: Preview and Test
- Use GTM’s Preview Mode to test the script.
- Check if users are correctly assigned to variants and redirected accordingly.
Setting Up Event Tracking in GA4
Step 1: Define Events
The script sends two events to GA4:
- experiment_entered: Tracks users entering the experiment. Includes the parameter experiment_group with values A or B.
- ab_test_assignment: Tracks all users and their assigned group (A, B, or Control).
Step 2: Create Custom Dimensions
- Go to Admin > Custom Definitions > Custom Dimensions in GA4.
- Create dimensions for:
- experiment_group (from experiment_entered).
- ab_test_variant (from ab_test_assignment).
Step 3: Validate Events
- Use GA4’s DebugView to verify the events.
- Confirm that the events include the correct parameters.
Analyzing Your A/B Test in GA4
Once the data starts flowing into GA4, use Exploration Reports to analyze your test:
- Users Entering the Experiment: Filter by the experiment_entered event to see how many users entered the experiment.
- Variant Distribution: Break down experiment_group to measure how users are split between version A and version B.
- Conversion Analysis: Combine this data with your conversion events to determine which variant performs better.
Setting up A/B testing with GTM and GA4 provides a powerful, flexible way to experiment and optimize your website. This script ensures you can measure participation and results accurately, giving you the insights needed to make data-driven decisions.
Need help implementing this script or analyzing your results? Contact us at Deeploy for expert assistance in A/B testing, analytics, and digital marketing optimization.