javascriptgoogle-analyticsgoogle-tag-manageranalytics.js

Passing UTM Tags to Google Analytics with Google Tag Manager in Javascript not working


I'm trying to send utms (medium, source) to Google Analytics directly in Javascript code (not via the URL), for every visit to my page. This is how I'm trying to do it:

<script async src="https://www.googletagmanager.com/gtag/js?id=UA-52626777-6"></script>
<script>
    window.dataLayer = window.dataLayer || [];
    function gtag(){dataLayer.push(arguments);}
    gtag('js', new Date());

    gtag('set', {
        'campaignName':'MyCampaignName',
        'campaignMedium':'MyMedium',
        'campaignSource':'MySource'
    });

    gtag('config', 'UA-11111111-1');

</script>

For some reason, even though Google Analytics is tracking pageviews in real-time correctly, it doesn't seem to be getting the Medium and Source. Both show (none) and (direct) respectively: enter image description here

Any idea what I'm missing here?


Solution

  • The config tag should fire AFTER the sets.

    Also gtag('set', {campaign: {medium: 'myMedium', source: 'mySource'}});