google-analyticsgoogle-tag-managergoogle-optimize

How can I set Analytics variables with Google Tag Manager from the server?


I'm using Google Optimize for creating A/B tests. I'm using it in server side mode as in this guide: https://developers.google.com/optimize/devguides/experiments

That guide shows an easy way of setting which experiment is running with which variant by rendering the JS code on the server which sets the experiment id and variant id:

  // 2. Create a tracker.
  ga('create', 'UA-XXXXX-Y', 'auto');

<?php
<<<HTML
  // 3. Set the experiment ID and variation ID.
  ga('set', 'exp', '$experimentId.$variationId');
HTML;
?>
  // 4. Send a pageview hit to Google Analytics.
  ga('send', 'pageview');

However I'm using Google Tag manager and so far haven't managed to find any guide that shows how to set variables from the server with it. ga is an undefined variable so the above doesn't work.


Solution

  • Since the GTM calls the normal snippet for each tag, you can set any field the analytics snippet understands even if they are not yet automatically listed in the tag editor drop down.

    For example, as a page view field: Fields to set

    Then set DataLayer variable so it can be received from the external source, for example: DataLayer Variable

    Leading to the fields using the variable in a finished Tag: Field using the DataLayer Variable

    Now, you can set DataLayer variable in the server side that will be passed through to the tag. Since I chose a page view, it would be best to pre-fill the dataLayer before loading the GTM so they are present before the initial tags fire, for example:

    <!-- Google Tag Manager -->
    <?php or other backend language wrapping...
     <script>window.dataLayer = [{exp:"$experimentId.$experimentVariant"}] 
     </script>
    ?>
    <script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
    new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
    j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
    'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
    })(window,document,'script','dataLayer','GTM-0');</script>
    <!-- End Google Tag Manager -->