Skip to content

This free GTM recipe gives you everything you need to launch simple, reliable A/B experiments—without investing in extra tools with monthly fees. It handles random user assignment, group segmentation, content hiding, and result tracking—all built with GA4 in mind.

Whether you're testing new headlines, layout tweaks, or UX changes, this setup helps you move from “we think” to “we know.” If your team is comfortable with HTML, CSS, and JavaScript, you can get your first experiment live in under an hour.

🗂️Download the import file here🗂️

This Google Tag Manager (GTM) setup provides a foundational framework for conducting simple A/B (or multivariate) tests directly within GTM.

Functionality:

  1. User Assignment: When a user first visits, they are assigned a random number (1-20) which is stored persistently in their browser's localStorage. This ensures they consistently see the same experiment version across sessions.

  2. Group Allocation: Based on the assigned number, users are categorized into 'control' or 'variant' groups for specific experiments (currently configured for a 50/50 split on a "homepage hero" experiment).

  3. Content Hiding: On pages designated for an experiment, a specific section of the page (defined as main#main-content) is briefly hidden and set to fade in using CSS transitions to minimize the 'flash' of original content before the experiment variation is applied.

  4. Conditional Logic: GTM triggers check the user's assigned group and the page they are on. Only the logic tag corresponding to the user's group (Control or Variant) will execute.

  5. Variant Implementation: The 'Variant' tag contains placeholder JavaScript to modify webpage elements (e.g., changing headline text, applying styles). This is the primary section requiring customization for each test.

  6. Tracking: Both Control and Variant tags push an experiment event to the dataLayer, including the experiment name and the variation name. A separate GA4 tag listens for this event and sends the data to Google Analytics 4 as an experiment_viewed event with relevant parameters.

Technical Skill Required:

  • Intermediate GTM Proficiency: You need to be comfortable working with Tags, Triggers, Variables (especially Custom JavaScript and Data Layer Variables), and understanding the GTM preview/debug process.

  • Basic HTML & CSS: Understanding HTML structure and CSS selectors is essential to target the correct elements for hiding/showing and for modification in the variant code.

  • Basic JavaScript: Implementing the actual changes for your experiment variations (the core of the 'Variant' tag) requires writing JavaScript to manipulate the DOM (Document Object Model) – finding elements and changing their text, style, classes, etc.

  • Troubleshooting: Debugging skills using browser developer tools (console, element inspection) are necessary if experiments don't behave as expected.

Truthfully, this is not a "no-code" solution. While the framework is reusable, deploying new experiments requires technical input, primarily for the JavaScript in the Variant tag.

Benefits of A/B Testing (and Using This Framework):

A/B testing is crucial for making data-driven decisions rather than relying on guesswork. By comparing how different versions of a page or element perform, you can:

  • Optimize Conversions: Improve rates for key actions like sign-ups, purchases, lead generation, etc.

  • Enhance User Experience: Identify changes that make your site easier or more enjoyable to use.

  • Reduce Risk: Test changes on a segment of users before rolling them out to everyone.

  • Build the Case for Investment: Even simple tests run via GTM can demonstrate the value of experimentation. Positive results from this framework can justify investing in more sophisticated dedicated A/B testing platforms and resources in the future. This setup allows you to start testing and gathering insights relatively quickly if you have the necessary GTM/web development skills in-house.


Detailed Instructions for Customization

Follow these steps to configure and reuse this framework for your experiments:

(Assumes you have successfully imported the JSON into your GTM workspace)

1. Prerequisite: Enable Built-In Variables

  • Go to "Variables" -> "Built-In Variables" -> "Configure".

  • Ensure Page Path and Event are checked and enabled.

2. Configure Core Variables:

  • JS - Experiment Group:

    • This variable determines which group ('control' or 'variant') a user belongs to based on their random number.

    • Edit this variable to adjust the test parameters:

      • controlThreshold = 10;: Users with randomAssignment <= 10 are 'control'.

      • variantThreshold = 20;: Users with randomAssignment > 10 AND <= 20 are 'variant'. (Adjust these for different splits, e.g., controlThreshold = 15 for a 75/25 split).

      • controlGroupName = 'control';: The value returned for the control group. Change if needed (e.g., 'original').

      • variantGroupName = 'variant';: The value returned for the variant group. This value MUST match the variationName set inside the Variant Logic Tag and the condition in the Variant Trigger.

      • errorGroupName = 'assignment_error_or_excluded';: Value for users outside defined thresholds or if assignment fails.

  • JS - testRandomAssignment:

    • Usually, leave this as is. It handles assigning a number 1-20 via localStorage. Only modify if you need a different range or storage mechanism (advanced).

  • experimentName / variationName:

    • These are Data Layer Variables used by the GA4 tag. They read the values pushed by the Control/Variant tags. Generally, leave these as configured unless you change the keys in the dataLayer.push.

  • ga4ID (Variable ID: 5):

    • Update this Constant Variable with your actual GA4 Measurement ID (e.g., G-XXXXXXXXXX). The GA4 tag uses this.

3. Configure Triggers:

  • Experiment - Pageview - Homepage - Control / ... - Variant:

    • These trigger the respective logic tags.

    • Edit these triggers to set where the experiment runs:

      • Condition 1 (Page Path): Currently Page Path matches RegEx \/(\?.+)? (which targets the homepage / potentially with query parameters). Change this to match the page(s) for your experiment (e.g., Page Path equals /your-product-page, or Page Path starts with /blog/). Both triggers must have the same Page Path condition.

      • Condition 2 (Group Check): This uses . Ensure the value (control or variant) matches the variantGroupName you set in the JS - Experiment Group variable.

  • Experiment - Homepage Experiment - Base:

    • This trigger fires the "Hide" tag (CH - Experiment - Base). 

    • Configure the Page Path: Set the condition on this trigger (under "This trigger fires on") to match the exact same Page Path condition you used for the Control/Variant triggers above. This ensures hiding only happens on the experiment page(s).

  • Experiment Viewed (GA4 Event):

    • This triggers the GA4 tag based on the dataLayer push. Usually, leave this as is (Custom Event equals experiment).

4. Configure Tags:

  • CH - Experiment - Base:

    • This tag hides the content while it's swapped.

    • Edit the code inside:

      • var selector = 'main#main-content';Crucially, update this CSS selector to target the specific container element on your page that you want to hide/fade during the experiment.

      • var transitionDuration = '0.6s';: Adjust the fade-in speed.

      • var transitionTiming = 'ease-in-out';: Adjust the fade style.

    • Ensure this tag's "Tag Firing Priority" (Advanced Settings) remains high (e.g., 100).

  • CH - Experiment - Homepage Experiment - Control:

    • Edit the code inside:

      • var experimentName = 'homepage hero';: Update with your specific experiment name for reporting.

      • var variationName = 'control';: Ensure this matches the controlGroupName from JS - Experiment Group.

      • var selector = 'main#main-content';Ensure this matches the selector used in the "Hide" tag (CH - Experiment - Base). This is for the reveal logic.

  • CH - Experiment - Homepage Experiment - Variant:

    • Edit the code inside:

      • var experimentName = 'homepage hero';: Update with your experiment name (match Control tag).

      • var variationName = 'variant';Ensure this matches the variantGroupName from JS - Experiment Group and the value in the firing trigger.

      • ### VARIANT-SPECIFIC JAVASCRIPT ### Section: This is where you write your own JavaScript.

        • Delete or modify the existing example (headline change).

        • Use document.querySelectordocument.getElementById, etc., to select the elements you want to change.

        • Use .textContent.innerHTML.style.classList.add() / .remove(), etc., to make your modifications.

        • This requires JavaScript knowledge. Test your JS carefully. Use console.log for debugging.

      • Reveal Section: var selector = 'main#main-content';: Ensure this matches the selector used in the "Hide" tag (CH - Experiment - Base).

  • GA4 - Experiment:

    • Fired by (Custom Event 'experiment').

    • Ensure "Configuration Tag" dropdown selects your main GA4 Config Tag (if you have one) OR that  is correctly set to your ID.

    • Verify "Event Name" (experiment_viewed) is what you want in GA4 reports.

    • Verify "Event Parameters" correctly map experiment_name to  (DLV) and variation_name to  (DLV).

5. Testing & GA4 Setup:

  • Use GTM Preview Mode extensively to test all paths: control group, variant group. Check console logs for errors or warnings. Verify elements hide/show/change correctly.

  • Use GA4 DebugView to confirm the experiment_viewed event is received with the correct experiment_name and variation_name parameters.

  • In GA4 Admin: Go to Custom definitions -> Custom dimensions -> Create custom dimensions. Register experiment_name (event scope) and variation_name (event scope) so you can use them in GA4 reports.

By carefully adjusting these components, particularly the triggers and the variant JavaScript, you can adapt this framework to run various A/B tests on your website.

Need help customizing this or designing smarter experiments?

Lightkeeper works with growing teams to turn data into action—through better tracking, sharper messaging, and testing that moves the needle. If you’re ready to build a culture of experimentation (without getting buried in tools), reach out here—we’d love to support your next growth step.