A/B Testing with Google Tag Manager (Measured in GA4)

Web Marketer

You can A/B test tags with Google Tag Manager (GTM) alone: use the built-in Random Number variable to split visitors into A and B, then fire either tag A or tag B through a custom event. The scripts inside the tags stay untouched, and removing the test afterwards is easy. This post covers the setup, a cookie that keeps each visitor in the same variant, and how to measure the result in GA4.

Updated December 2026: Re-checked the steps and specs in the current GTM (Random Number value range, Custom JavaScript variable format, consent setting labels), and added cookie-based variant persistence, Consent Mode v2 caveats, GA4 measurement with a custom dimension and Explorations, and sample-size estimates.

Goal: fire one of two GTM tags at random

This post shows how to set up an A/B test in Google Tag Manager (GTM) that compares two tags without changing their configuration. The main goal is to fire two tags (tag A and tag B) at random and see which one performs better.

If you have been stuck since Google Optimize shut down, this approach shows that you can run a simple A/B test in GTM without adding another service.

One advantage of GTM is that marketers can add and manage site tags without asking an engineer. To keep that advantage while comparing tags, this method controls whether a tag fires instead of editing what is inside it.

A/B testing options after Google Optimize

Google Optimize and Optimize 360 were sunset on September 30, 2023, and all experiments still running at that point ended. Google points users to third-party testing tools that integrate with GA4, such as AB Tasty, Optimizely and VWO ([Sunset September 2023] Google Optimize - Analytics Help). As of December 2026, GTM itself has no dedicated A/B testing feature.

MethodBest forCaveats
Split tags in GTM (this post)Comparing things at the tag level: tracking tags, chat widgets, banner scripts. No extra costYou handle the statistics and traffic allocation yourself. Not suited to tests that change the page's look in detail
A/B testing tools (AB Tasty, Optimizely, VWO, etc.)Comparing page design and copy, multivariate testsMostly paid. Their snippets need anti-flicker handling
Server-side or CMS-side splitTests that change the page structure itselfRequires engineering work

Who this post is for

  • You lost Google Optimize, haven't picked a replacement, and want to run A/B tests entirely in GTM
  • You want to A/B test tags without editing their contents
  • You want to set the traffic split manually

How it works

There are two test tags, tag A and tag B, plus one control tag that decides which of them fires. The control tag generates a random number and uses it to pick the tag.

Tags A and B are fired by custom events, which makes it easy for the control tag to trigger them. The downside is more tags and triggers to manage; the upside is that you don't have to modify the scripts in tag A or tag B.

Pros

  • Easy to remove when the test ends
  • The tag scripts are reused as they are

Cons

  • More triggers and tags to manage
  • Unless you record the assignment, you can't tell later which variant a visitor saw (solved by the GA4 setup below)

Implementation and testing

With the overall flow in mind, let's build it and check that it works.
These are the tags and triggers involved.
We'll set them up in order.

TypeNameRole
TagA/B test controlUses a random number to decide whether tag A or tag B fires
TagTag AVariant A of the test
TagTag BVariant B of the test
TriggerTag A triggerFires tag A
TriggerTag B triggerFires tag B

The A/B test control tag

Start with the most important piece, the control tag.

A/B tests usually split traffic with a random number,
which lets tag A and tag B fire at random.
GTM has a random number built in, so we'll use that.

In GTM, open Variables, click Configure under Built-In Variables and check Random Number.
According to the official help, this variable is set to a random number between 0 and 2147483647 (still the case as of December 2026).

Next, create the control tag with the Custom HTML tag type and paste the code below.
It normalizes the random number to a value between 0 and 1 and compares it with a threshold that sets the split.
In this example, tag A and tag B each fire 50% of the time.
To fire tag A 90% of the time, set threshold=0.9.

<script>

// Share of traffic that fires tag A
var threshold = 0.5 // 1:1 A/B split

// 0 to 2147483647
var random = {{Random Number}}
// Normalize to 0 - 1
var standardRandom = random / 2147483647.0

// Initialize
window.dataLayer = window.dataLayer || []

if (threshold > standardRandom) {
   window.dataLayer.push({event:"Atag"})
}else{
   window.dataLayer.push({event:"Btag"})
}

</script>

Here, a custom event called Atag fires tag A and a custom event called Btag fires tag B.

This example uses the All Pages trigger for the control tag; change it to suit your site.

Improved version: keep each visitor in one variant with a cookie

The code above draws a new random number on every page view, so the same person can see A on the first page and B on the second. That works as a tag-firing test, but it is not a user-level A/B test of the kind "did people who saw A or people who saw B submit more inquiries?". Save the variant chosen on the first visit in a first-party cookie and reuse it afterwards.

<script>
(function () {
  var COOKIE_NAME = 'gtm_ab_tag';  // use a new name for each test
  var threshold = 0.5;             // share of A
  var m = document.cookie.match(new RegExp('(?:^|; )' + COOKIE_NAME + '=([AB])'));
  var variant = m ? m[1] : null;

  if (!variant) {
    // assign once and keep for 30 days
    variant = ({{Random Number}} / 2147483647 < threshold) ? 'A' : 'B';
    document.cookie = COOKIE_NAME + '=' + variant +
      '; path=/; max-age=' + (60 * 60 * 24 * 30) + '; SameSite=Lax';
  }

  window.dataLayer = window.dataLayer || [];
  window.dataLayer.push({
    event: variant === 'A' ? 'Atag' : 'Btag',
    ab_variant: variant
  });
})();
</script>

The custom event names (Atag / Btag) are the same as before, so the triggers and the A/B tags work unchanged. The new ab_variant key is used for the GA4 setup below. I ran this assignment logic in Node.js with an object that mimics document.cookie: over 100,000 assignments the share of A was about 50% (0.4995), and the stored value was reused on later calls. Always confirm the in-browser behavior in GTM Preview.

You could also return the variant from a GTM Custom JavaScript variable, but such a variable must take the form of an anonymous function that returns a value (User-defined variable types for web - Tag Manager Help), and variables are evaluated every time they are referenced. Code with side effects, such as writing a cookie, is easier to reason about in a tag, as in this post. If you only need to read the stored value, the 1st Party Cookie user-defined variable (Cookie Name gtm_ab_tag) is handy.

Triggers

Next, set up the triggers that fire tag A and tag B.

Go to Triggers, create a new trigger, choose the Custom Event trigger type and enter Atag as the event name.

Do the same for Btag.

If tag A or tag B already had a trigger such as All Pages, remove it; otherwise the tag fires every time, regardless of the test. If you need to keep the existing trigger, you can add the other variant's custom event (Btag for tag A) as an exception in the tag's Triggering section. However, an exception only blocks a tag when it fires on the same event, so it can't exclude across triggers that fire at different moments, such as All Pages (a page view) and a custom event. When in doubt, follow the structure in this post: give the A/B tags only their custom event triggers.

The A/B test tags

Now add the tags you actually want to compare.

Since this is a test, each tag here is a Custom HTML tag that calls alert, so you can see whether A or B fired.
Attach the tag A trigger and the tag B trigger you just created to the respective tags.

That completes the setup.

Check it in Preview mode

Finally, confirm that it works in Preview mode.

Click Preview at the top right of GTM. Tag Assistant opens; enter the URL of the site you want to test and connect.

You're done when each page load shows the alert from tag A or tag B (recorded in 2024. With the cookie version the same browser always gets the same alert; to see the other variant, delete the gtm_ab_tag cookie in your browser's developer tools and reload).

When tag A fires

The alert set in tag A runs.

When tag B fires

Likewise, the alert set in tag B runs.

Consent Mode v2 and cookie consent

The improved control tag writes a cookie. If your site has visitors from regions that require cookie consent, such as the EEA, the tag must not run before consent. In GTM, set it up like this (Tag Manager consent mode support - Tag Manager Help):

  1. Go to Admin > Container Settings and, under Additional Settings, select Enable consent overview.
  2. In the control tag, open Advanced Settings > Consent Settings, choose Require additional consent for tag to fire and add analytics_storage (or functionality_storage, depending on the purpose).
  3. This assumes your consent management platform (CMP) sets the default consent state on the Consent Initialization - All Pages trigger.

Consent Mode v2 added two parameters to the existing ad_storage and analytics_storage: ad_user_data (sending user data to Google for advertising) and ad_personalization (personalized advertising). To keep using Google's advertising features, such as remarketing, for EEA users, you need to pass these consent signals to Google (Updates to consent mode for traffic in European Economic Area (EEA) - Tag Manager Help).

For the A/B test, keep in mind that users who decline consent are left out of the test. You end up comparing people who accepted cookies, which may differ from your audience as a whole. Sites aimed at Japan may also need to disclose such data transmission in a privacy policy under Japan's external transmission rules (the amended Telecommunications Business Act, 外部送信規律), so check your own rules before rollout.

Measuring the result in GA4

The original post skipped evaluation, but you can only decide an A/B test once you measure how many people who saw each variant converted. Here is how to do it in GA4.

1. Send the assignment as an event

  1. Under Variables, create a user-defined Data Layer Variable with the Data Layer Variable Name ab_variant (for example, name it "DLV - ab_variant").
  2. Create a trigger of type Custom Event, enter ^(Atag|Btag)$ as the event name and check Use regex matching.
  3. Create a Google Analytics: GA4 Event tag with the event name ab_test_view, add the event parameter ab_variant = {{DLV - ab_variant}}, and attach the trigger from step 2. If you run several tests at once, also send an ab_test_name parameter to tell them apart.

2. Register a custom dimension

In GA4, go to Admin > Custom definitions, click Create custom dimension, set the scope to Event and the event parameter to ab_variant. It takes 24–48 hours before you can use it in reports and explorations, and a standard property allows up to 50 event-scoped custom dimensions ([GA4] About custom dimensions and metrics - Analytics Help). Parameters sent before you register the dimension won't show up in it afterwards, so register it before the test starts.

3. Compare in Explore

  1. In GA4, go to Explore and create a Free form exploration.
  2. Create two user segments: "Event name = ab_test_view" with the parameter "ab_variant = A" (and B for the other).
  3. Drop both segments into Segment comparisons and add Total users, Key events and User key event rate as values.
  4. Mark the outcomes you want to compare (completed inquiry, brochure request, etc.) as key events in advance.

The exploration layout and how to build segments are covered in detail in How to use GA4 Explorations. Explorations only cover the data retention period (2 or 14 months), so set retention to 14 months if you plan a long test.

First check that Total users per segment roughly matches the split you set (about half and half for 50:50). If it is far off, suspect an implementation problem, such as an error in one of the tags or consent settings blocking only one side.

Sample size to check before you call a winner

To say a difference between A and B isn't chance, you need more users than most people expect. With a two-sided test, 5% significance level and 80% power, the normal-approximation formula gives the following users per variant to detect a difference in conversion rate (my own estimates, calculated in Python).

Conversion rate AConversion rate BUsers needed per variant
2.0%2.5%~13,800
2.0%3.0%~3,800
5.0%6.0%~8,200
10.0%12.0%~3,800
  • The smaller the difference you want to detect, the faster the required sample grows. For a site with a few thousand users a month, stick to tests where you expect a large difference.
  • Checking every day and stopping as soon as the result looks significant raises the chance of a false positive. Fix the duration or sample size in advance, and run in whole weeks (at least one to two) to avoid day-of-week bias.
  • GA4 explorations may be sampled when there is a lot of data, and adding demographic dimensions can drop rows because of data thresholds. Read the numbers you decide on when the icon at the top right is green (unsampled).

Ending the test

Delete the losing tag and the control tag, then move the control tag's trigger to the tag you keep. That's all it takes to wrap up.

If you added the GA4 setup, delete (or pause) the ab_test_view event tag and its trigger as well. With the cookie version, the gtm_ab_tag cookie can remain for up to 30 days, but once the control tag is gone nothing reads it, so it does no harm. Use a different cookie name for your next test.

Summary

This post showed how to A/B test tags with custom events while leaving the tags themselves untouched. You only change triggers and add a control tag; the contents of tag A and tag B stay as they are.

For real use, add three things: keep each visitor in one variant with a cookie, send the assignment to GA4 as an event parameter, and compare key event rates in Explore. Since the method uses a cookie, configure consent mode and estimate the sample size before you start.

I hope this helps.

created by Rinker
¥1,760 (2024/11/03 02:43:10時点 楽天市場調べ-詳細)

 

References

Title and URL copied