Passing custom dimensions with gtag

Dmytro Bulakh
1 min readJan 28, 2020
Oh, no gtag snippet here :(

Analytics documentation describes the usage of custom dimensions in a clear way: first, define a custom map with a config command and then pass values as parameters while sending events:

// Configures custom dimension<Index> to use the custom parameter
// 'dimension_name' for 'GA_MEASUREMENT_ID', where <Index> is a number
// representing the index of the custom dimension.
gtag('config', 'GA_MEASUREMENT_ID', {
'custom_map': {'dimension<Index>': 'dimension_name'}
});

// Sends the custom dimension to Google Analytics.
gtag('event', 'any_event_name', {'dimension_name': dimension_value});

However, this approach has some drawbacks. It doesn’t allow you to send custom dimension value alongside pageview hit, which may be crucial for some content reporting. Luckily there’s quite a simple workaround. You may use gtag(‘set’) command to define custom_map before config in the same way as you define other persistent values, and then just use defined mapping as a parameter to your gtag(’config’) call:

<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
//Call 'set' before config to define mapping
gtag('set',
{
'custom_map':
{
'dimension1': 'test_cs1'
}
});
// use mapping within 'config' command
gtag('config', 'UA-XXXXXXX-1', { 'test_cs1': 'some fancy value' });
</script>

--

--

Dmytro Bulakh

Marketing professional, Google Analytics and Google AdWords certified specialist at ppchead.com, beer lover and football aficionado