# Send A/B test data to Google Analytics, GTM and Mixpanel

export const metadata = guideMeta("subscribing-to-events");

Testa reports your experiment results. You probably also have Google Analytics
4, Mixpanel, Amplitude or a data warehouse where the rest of your product and
marketing data lives. Sending each visitor's experiment and variation there lets
you answer questions an A/B testing dashboard can't, such as *"did the new
pricing page change 30-day retention?"* or *"how did variation B perform for
paid social traffic?"*

Testa's integration script emits **browser events** when it assigns and applies
a variation. Subscribe to them and you can forward the data to any tool with a
few lines of JavaScript.

## The two events

| Event | When it fires | Use it for |
| --- | --- | --- |
| `variation_assigned` | Right after the visitor is assigned a variation, **before** any redirect or HTML change | Recording assignment for split URL tests, where the visitor is about to be redirected |
| `variation_applied` | **After** the variation has been applied to the page | Recording exposure for Edit HTML tests: the visitor has actually seen the change |

Both events pass the same `data` object to your listener:

```js
{
  project_id: 123,             // your Testa project ID
  experiment: 456,             // experiment ID
  variation: 1,                // variation ID (0 = control)
  uuid: "abc-123-def-456",     // the visitor's Testa ID
  title: "Homepage Hero Test", // experiment name
  url: "https://example.com/", // current page URL
}
```

## Subscribing to events

Register listeners on `window.Analytica.listeners` **before** the Testa script
loads, so no event is missed. Each listener is an `[eventName, handler]` pair:

```html
<script>
  window.Analytica = window.Analytica || {};
  window.Analytica.listeners = window.Analytica.listeners || [];

  window.Analytica.listeners.push([
    "variation_applied",
    function (data) {
      console.log("Testa variation applied:", data);
    },
  ]);
</script>
<!-- Your Testa snippet goes after this -->
```

Open your site, check the console, and you'll see one log line for each
experiment you're in. This is also the fastest way to check that an experiment
is running and that targeting works as you expect.

## Google Analytics 4 (gtag.js)

GA4 has a recommended event for third-party experiment tools:
`experience_impression`, with the experiment and variant in the
`exp_variant_string` parameter. Using it keeps your reports consistent if you
ever switch testing tools.

```js
window.Analytica.listeners.push([
  "variation_applied",
  function (data) {
    if (typeof gtag !== "function") return;
    gtag("event", "experience_impression", {
      exp_variant_string: "TESTA-" + data.experiment + "-" + data.variation,
      experiment_name: data.title,
    });
  },
]);
```

To compare variations in GA4 reports, register `exp_variant_string` (and
`experiment_name` if you send it) as **custom dimensions** under *Admin → Custom
definitions*. You can then build an exploration that breaks down conversions,
revenue or engagement by variant.

## Google Tag Manager

With GTM, push the data to the `dataLayer` and route it from there to GA4, ad
platforms or anything else:

```js
window.Analytica.listeners.push([
  "variation_applied",
  function (data) {
    window.dataLayer = window.dataLayer || [];
    window.dataLayer.push({
      event: "testa_variation_applied",
      experiment_id: data.experiment,
      experiment_name: data.title,
      variation_id: data.variation,
    });
  },
]);
```

Then in GTM:

1. Create **Data Layer Variables** for `experiment_id`, `experiment_name` and
   `variation_id`.
2. Create a **Custom Event trigger** for `testa_variation_applied`.
3. Create a **GA4 Event tag** (or any other tag) that fires on that trigger and
   sends the variables as event parameters.

## Mixpanel

```js
window.Analytica.listeners.push([
  "variation_applied",
  function (data) {
    mixpanel.track("Experiment Viewed", {
      experiment_id: data.experiment,
      experiment_name: data.title,
      variation_id: data.variation,
    });
  },
]);
```

To segment *every* later event by variation, not just the exposure event, also
register it as a super property inside the same listener:

```js
// inside the variation_applied listener above
mixpanel.register({ ["testa_exp_" + data.experiment]: data.variation });
```

## Segment

Segment's A/B testing spec defines an `Experiment Viewed` event, which downstream
destinations such as Amplitude, warehouses and ad platforms understand:

```js
window.Analytica.listeners.push([
  "variation_applied",
  function (data) {
    analytics.track("Experiment Viewed", {
      experiment_id: String(data.experiment),
      experiment_name: data.title,
      variation_id: String(data.variation),
    });
  },
]);
```

## Split URL tests: use `variation_assigned`

In a split URL test, the visitor is redirected to the variation URL.
`variation_applied` might not reach your analytics before the browser navigates
away. Listen to `variation_assigned` instead. It fires before the redirect:

```js
window.Analytica.listeners.push([
  "variation_assigned",
  function (data) {
    window.dataLayer = window.dataLayer || [];
    window.dataLayer.push({
      event: "testa_variation_assigned",
      experiment_id: data.experiment,
      variation_id: data.variation,
    });
  },
]);
```

If your analytics library supports it, send this event with a beacon transport
(for example, GA4's `transport_type: "beacon"`), so the request survives the
page unload.

## Sending each assignment once per session

A listener runs whenever the event fires. If you only want one exposure event
per experiment per session in your analytics, guard it with `sessionStorage`:

```js
window.Analytica.listeners.push([
  "variation_applied",
  function (data) {
    var key = "testa_sent_" + data.experiment;
    try {
      if (sessionStorage.getItem(key)) return;
      sessionStorage.setItem(key, "1");
    } catch (e) {}
    // ...send to your analytics here
  },
]);
```

## Troubleshooting

- **Nothing fires.** Check that your listener code runs *before* the Testa
  snippet, and that you are actually in an experiment. Targeting, exclusions or
  traffic allocation may be keeping you out. Try a private window.
- **`gtag` or `mixpanel` is undefined.** Your analytics library may load after
  Testa. Guard the call (as in the GA4 example) or switch to the `dataLayer`,
  which queues events until GTM is ready.
- **Variant counts in GA4 don't match Testa.** Some difference is normal. Ad
  blockers, consent banners and sampling all affect analytics tools differently.
  Use Testa's results for the test decision and your analytics for deeper
  segmentation.

## FAQ

### What does `variation: 0` mean?

`0` is the control (the original version). Variations are numbered from there.

### Can I use these events to trigger my own code?

Yes. Any JavaScript can run in a listener, for example showing a different chat
widget for one variation or tagging the visitor in your CRM.

### Do these events replace Testa's goal tracking?

No. They send experiment data *out* to other tools. To record conversions in
Testa, use [goals](/docs/experiment-setup/goals), for example a custom event
sent with `window.Analytica.pushEvent`.
