One of the things I’ve recommended from the get-go is to always send the Client ID to Google Analytics with your users’ hits. This is very useful for adding a level of granularity to your tracking. At first, I recommended using an Event tag to do this. Then I modified my approach a little so that you could send it with your initial Page View (thus not inflating your hit counts).

However, Universal Analytics recently released a new task API, customTask, which lets you access the model object mid-tag, thus letting you modify the payload that is dispatched to Google Analytics. In this article, I’ll show you how this works by using the classic example of sending the Client ID to Google Analytics.


The Simmer Newsletter

Subscribe to the Simmer newsletter to get the latest news and content from Simo Ahava into your email inbox!

Tip 59: Access the model object mid-tag in Google Tag Manager

The setup is really simple. You need a Custom Dimension setup in Universal Analytics, and then you simply need to add a new Field to set in your Page View tag (or whatever you want to use to send the data to GA). Remember to read my article on sending this type of metadata to Google Analytics, if you’re unsure why you would want to do this in the first place.

The tag setup would look like this:

Field name should be set to customTask, and as its value you need to use a Custom JavaScript Variable. The variable looks like this:

function() {
  // Modify customDimensionIndex to match the index number you want to send the data to
  var customDimensionIndex = 5;
  return function(model) {
    model.set('dimension' + customDimensionIndex, model.get('clientId'));

What happens is that once Google Tag Manager starts executing the tag code, it first encounters the customTask field. It resolves the variable to a closure, which is basically a function that automatically receives a model object as a parameter. The model object can be manipulated using the get and set methods.

Next, we set the Custom Dimension at index 5 (as determined by the value of customDimensionIndex) to the Client ID, which we retrieve with the get method of the model object.

This little trick means that we can tell the GA tag to fetch the Client ID from the tracker object and send it in a Custom Dimension without any extra hacks or workarounds that we had to employ previously. The fact that customTask has no other function in Universal Analytics means that we don’t have to mind the fact that we’re overwriting a task method with this tag.

You can use this for any fields in the model/tracker object if you wish.