google-analyticsgtag.jsgoogle-optimize

Optimize server side Experiments gtag


The docs for Google optimize server side events are written for analytics.js is there a way to do the same thing using gtag.js? https://developers.google.com/optimize/devguides/experiments#add-ga-tracking-code-to-variations

ga('set', 'exp', `${experimentId}.${variationId}`);
ga('send', 'pageview');

I'm using gtag so I need something like this:

gtag('event', '???', {
???: `${experimentId}.${variantPosition}`,
});

I tried these:

window.gtag('set', { expId: <experiment-id> });
window.gtag('set', { expVar: <variation-number> });
window.gtag('event', 'page_view', ...

and

window.gtag('config', 'UA-XXXXXXX-X', {experiments: [ { id: 'ExperimentID 1', variant: '1' }, { id: 'ExperimentID 2', variant: '2' }, ]});

Neither of these works, in optimize Details tab I cannot see any active sessions. Anyone solved this issue before?


Solution

  • So I managed to find a solution, for anyone wondering how to do it, this is it:

    window.gtag('config', 'UA-XXXXXXXX-XX', {
      experiments: [{ id: experimentId, variant: experimentVariation }],
    });
    

    where experimentId is id supplied by Optimize and variant is a digit representing active user experiment, for example 1 or 2.