Google Optimize experiment events back to Segment

Not a question but rather a sample of the code we use. Could be helpful for someone

For our product, we enabled Google Optimize via Segment integration. However, we wanted to receive events about any particular experiment back to Segment -> Warehouse for deep analytics. In order to achieve this, we added following simple code to our page that using Google Optimize API

// DataLayer initialization in head of page
window.dataLayer = window.dataLayer || [];

function gtag() {

// Code that listens to Optimize events
function reportExperimentEvent(variantId, experimentId) {
  if (variantId == undefined) {
    // Experiment was deactivated
  } else {
    // Experiment triggered for user.
    // For MVT experiments the variantId that will be provided from your experiment
    // will include the indexes for all section variants separated by dash ("-").
    analytics.track("Experiment Viewed", {experiment_id: experimentId, variant_id: variantId});

// Register experiments listener
gtag('event', 'optimize.callback', { callback: reportExperimentEvent });
Reply Oldest first
  • Oldest first
  • Newest first
  • Active threads
  • Popular