Google Tag Manager & Optimize Server-Side experiment sending variation

Solved by explicitly specifying a tracker id.

I used Analytics Debugger Chrome by Google to debug the issue and found that Google Tag Manager (GTM) made the tracker id gtm1 so I had to prefix things with that.

To find out your tracker ID, call ga.getAll()[0].get('name') (may be gtm1, gtm2, etc.).

Changed my setGAExperiment function to the following

function setGAExperimentCX(_expId, _vId){
    ga('gtm1.set', 'exp', _expId.toString() + '.' + _vId.toString());

    // this forces the above exp set to be sent to GA, you can name the event whatever you want with whatever values you want
    ga('gtm1.send', 'event', 'Experiment', 'Trigger', _expId.toString() + '.' + _vId.toString());
}

The function that calls setGAExperimentCX is

function performNewCartExp(_vId) {
    if (typeof ga == "undefined") {
        if (_performNewCartExp != undefined) { clearTimeout(_performNewCartExp); }
        _performNewCartExp = setTimeout(function () { performNewCartExp(_str); }, 250);
    } else {
        setGAExperimentCX('XXXXXXXXXXX', parseInt(_vId, 10));
    }
}

You can set Google Analytics variables on page load by using the 'Fields To Set' option in Google Tag Manager.

  1. Open your Universal Analytics Tag in GTM
  2. Click Enable overriding settings in this tag
  3. Click More Settings > Fields to Set
  4. Create a new field called expId. This field should contain the alphanumeric experiment id XXXXXXXXXXX.
  5. Create a new field called expVar. This field should contain the experiment variant number (0 for original, 1, 2, 3 etc for custom versions)

Important: Make sure that the optimize tag get's triggered before the analytics tag.

In my case I used a Custom Javascript variable for the expId and expVar fields, which used some custom code to get the correct experiment ID and version ID.

I figured the field names out by checking out the 'Analytics Field Reference' page:

https://developers.google.com/analytics/devguides/collection/analyticsjs/field-reference#expId

https://developers.google.com/analytics/devguides/collection/analyticsjs/field-reference#expVar

This method is probably preferred over your own answer, since it doesn't require any extra events to be triggered. Besides that you can configure this in GTM completely.

Screenshot for reference:

enter image description here