DEV Community

Cover image for dataLayers & Google Tag Manager & GA4 for Developers
Erman Küplü for Analyzify

Posted on • Updated on • Originally published at dev.to

dataLayers & Google Tag Manager & GA4 for Developers

I am always amazed by the full-stack developer's knowledge, experience, and learning habits. They use too many tools at the same time and know most of them easy as winking.

One topic I am surprised though is not many developers know about dataLayers, Google Tag Manager; and how they can be a great combination to track the key metrics, funnels and gather a valuable amount of information.

We use dataLayers and Google Tag Manager mostly for analysis, reporting - but even for debugging purposes by tracking user behavior in-depth.

In this post, I will give you a high-level overview of how dataLayers, GTM, and GA4 can be used to track important user metrics and even find the problems!

Have any questions? Ask in the comments and I'll do my best to answer!

Case Study on dataLayers & Google Tag Manager

We have created a complex web application that would take users eight steps to complete their orders because the purchase process required a lot of customization.

The Problem

We had a serious problem. The conversion rate was quite low. We were losing a lot of clients in the funnel.

What We Did

The classic funnel tracking wasn't working for us because the URL wasn't changing at every step. Also, the classic funnel tracking doesn't allow you to pass extra data. So we needed to set up advanced dataLayers and send relevant data on each step. I will walk you through in this case study on:

  • How we used dataLayers to track important events and collect important information,
  • How we processed the dataLayers through Google Tag Manager,
  • How we passed the data into Google Analytics 4,
  • How we make meaningful FUNNELS to clearly understand bottleneck and user behavior on Google Analytics 4.

Let's get started!

What is a Data Layer?

Data Layer is one of the most essential concepts in the data-analytics world. It is like the main storage for certain events and relevant data where you, developers, or 3rd-party-tools tools can temporarily store data (about user, page content, etc.). You can also watch this video - where I demonstrate what a dataLayer is and how it works.

Let's immediately jump into the example:

<script>
window.dataLayer = window.dataLayer || [];
window.dataLayer.push({
 'event': 'form_submitted',
 'formLocation': 'footer'
 });
</script>
Enter fullscreen mode Exit fullscreen mode

This could be a simple example of a form-submission event. You could push this dataLayer code once the form is successfully submitted. Nothing will happen if you only do this. You will need to listen & process this data using Google Tag Manager. We will visit in the next steps.

DataLayers can include more complex data as well. Check the example below for Google Analytics 4's addToCart event.

// Measure when a product is added to a shopping cart
dataLayer.push({
  'event': 'add_to_cart',
  'ecommerce': {
    'items': [{
      'item_name': 'Donut Friday Scented T-Shirt', // Name or ID is required.
      'item_id': '67890',
      'price': '33.75',
      'item_brand': 'Google',
      'item_category': 'Apparel',
      'item_category2': 'Mens',
      'item_category3': 'Shirts',
      'item_category4': 'Tshirts',
      'item_variant': 'Black',
      'item_list_name': 'Search Results',
      'item_list_id': 'SR123',
      'index': 1,
      'quantity': '2'
    }]
  }
});
Enter fullscreen mode Exit fullscreen mode

If you want to see another example, you can check out Analyzify Shopify DataLayers.

How we used dataLayers to track complex funnels

Our application has an 8-step complex, multilayered purchase process. That's why we added dataLayers on each step - and also included the relevant information.

Always make sure to create/open a window dataLayer object before you push any data.

<script>
window.dataLayer = window.dataLayer || [];
</script>
Enter fullscreen mode Exit fullscreen mode

1st Step:

dataLayer.push({
            'event': 'signup-steps',
            'step': '1',
            'stepname' : 'GetStarted'
        });
Enter fullscreen mode Exit fullscreen mode

2nd Step:

dataLayer.push({
            'event': 'signup-steps',
            'step': '2',
            'stepname' : 'Address',
                        'client-type':'Personal' //here we are passing the information that we received in the previous step
        });
Enter fullscreen mode Exit fullscreen mode

7th Step:

dataLayer.push({
            'event': 'signup-steps',
            'step': '7',
            'stepname' : 'Payment',
                        'uid': '12345', //the system generated a user ID in the 3rd step and we are now pushing it at each step
                        'payment-type' :'iFrame' // the user chose the payment type in the previous step
        });
Enter fullscreen mode Exit fullscreen mode

8th Step:

dataLayer.push({
            'event': 'signup-steps',
            'step': '8',
            'stepname' : 'iFrame',
                        'uid': '12345',
                        'iFrame-ID' :'iFrame-ID' // the user chose the payment type in the previous step
        });
Enter fullscreen mode Exit fullscreen mode

Final Step:

dataLayer.push({
            'event': 'signup-steps',
            'step': '9',
            'stepname' : 'ThankYou',
                        'uid': '12345',
                        'order-ID' :'order-ID'
        });
Enter fullscreen mode Exit fullscreen mode

We have now pushed all the relevant information and user actions to dataLayer. It is time to process them using Google Tag Manager.

Data Layer & Google Tag Manager

You need to have a Google Tag Manager account and the GTM snippet should be inserted into your application to achieve this result. To understand the process better, you can check out this article where we set up GTM on Shopify. You will see there how to add and debug a GTM container.

Create a custom event trigger on GTM

We first need to create an event trigger in GTM. We named our event as 'event': 'signup-steps' in the dataLayer. So follow along:

Go to Google Tag Manager > Triggers (Left) > Create New
GTM create trigger

Name the Trigger nicely, and choose CUSTOM EVENT from the Event Types:
GTM event types

Use the exact same name as you pushed into the dataLayer >
GTM custom event

Now we have the trigger. So the GTM will listen to this event carefully.

Create Custom Variables on GTM

Now it is time to create variables for the data that we are passing with the dataLayers. In the example above, we have step, stepName, uid, order-ID, iFrame-ID. Each of them should be created a separate custom variable - if we want to pass this data into Google Analytics or another platform.

Go to Google Tag Manager > Variables (Left) > New (Scroll down to see User-Defined Variables)

Similar to the above, we need to choose the Variable type. Choose DATA LAYER VARIABLE and name it correctly. We usually use a prefix dlv - so it looks like this dlv - user ID
GTM dataLayer variable

Make sure to use the exact same name as in the dataLayer:
GTM create custom variable

In the example here, I have only created one variable. You should create all of them one-by-one.

Google Tag Manager Debug DataLayers & Variables

Only a few times in my career, I could complete and publish the data setup without needing to change it. It never works in the first place :) That's why the debug process is crucial and needs to be done after every data implementation.

Once you are sure the GTM installed on your website >

Go to Google Tag Manager > Click Preview > Enter Your URL
GTM Debug Mode 1

Enter your URL and click START. The window should open your website in the new tab and the "Debugger Connected" should be visible at the right-bottom corner.
GTM Debugger Connected

Once you see this, go back to the Tag Assistant tab on your browser and you should be seeing something like this >
GTM Tag Assistant

Now go back to your site and take a few of the actions that you are pushing the dataLayer for. Once you are back to the Tag Assistant, you should be seeing the event names and dataLayer details in the screen >
GTM - Event dataLayer debug
These are dataLayers, now let's check if the variables we created are in place. Click the event name from the left, and then choose "Variables" from the tabs. You should be seeing the values.
GTM custom variables debug

If you are not seeing it this way, most probably you have just misspelled the names. Make sure to double-check with the names in your dataLayers.

image

Using Variables in GTM

As we have the events and variables, it is time to use them. We can pass that data to other parties such as Google Analytics, Facebook Pixel, and many others. In this example, I will create a Google Analytics 4 Custom Event and pass some of the data we collected.

We will now CREATE a NEW TAG. Go to GTM > Tags > Add New
GA4 Event Tag - GTM
Choose Google Analytics 4 Event and name the tag properly. If you didn't add the GA4 tag before, you need to configure it first. Very easy, so I will skip that one. You can check this video if you don't know how to add GA4 with GTM.

Choose your configuration and name the event properly.
GA4 Event Tag - GTM - 2

Now we will add custom variables. We will use EVENT PARAMETERS for event-based data and USER PARAMETERS for user-based data. Make sure to do something similar with the screenshot. A quick tip - when you write {{ on the right side - the variables will be listed so that you can choose the ones that you just created.

GTM - GA4 Custom Parameters

Make sure that it looks like this. The parameters name on the left and variable names on the right >
GTM - GA4 Custom Parameters - 2

It is not done yet! We need to choose the trigger. We should choose the custom event we have created above so that this event will only be triggered when the expected action happens.

Click this >
GTM Tag Triggers

And then choose the trigger you recently created >
GTM Tag Triggers 2

Now all should be set, SAVE and then Publish the container. Submit from the right-top corner and then Publish.

Debug One Last Time!

I mentioned above. Data setup mostly doesn't work the first time. After you publish the changes, click PREVIEW mode again and type your URL. Do the desired actions and then you should be seeing tags, triggers, variables just like below >
GTM - GA4 Events Debug

Google Analytics 4 Custom Events & Funnels

Even though GA4 is quite new, I have been fortunate to work with Google Analytics 4 intensely because of our GTM App for Shopify. GA4 is still under development and has some bugs but I love it and every day even more.

GA4 has many great features, and I mentioned the most important GA4 qualities in a blog post.

Now I will show you how to add custom events, parameters, data to GA4 and make funnels.

GA4 Custom Event Parameters

Make sure to register GA4 and add the global tag through GTM first. If you are not seeing a similar screen as below, you are probably not in Google Analytics 4 - but in the old one.
Click Custom Definitions > Create Custom Dimensions
Custom Definitions - GA4

To be able to achieve this, you need to run some test user interaction so that GA4 receives your event data. If you don't see your new data-name here; wait for some time and try again. It can also be visible the next day.

GA4 Event Parameters

Once you complete this step, you are sending all the data to GA4 perfectly and you are ready to create your amazing funnels. I will have another article on that so stay tuned!

Any questions? Did you face any problems? More than happy to answer.

Top comments (5)

Collapse
 
stephanreynolds profile image
Stephan Reynolds ✪

Great tutorial. How can I pass the values & events into Google Analytics as events or goals?

Collapse
 
ekuplu profile image
Erman Küplü

Thanks, Stephan! That's definitely a good question and I should make another tutorial for that. I'll write here quickly though.

For Universal Analytics, you just need to create a new "Google Analytics UA Event" tag in GTM and then you can use variables in ACTION or LABEL fields.

GA4 is more complex. Please check the following videos, they'll give you a great understanding of this topic - youtube.com/watch?v=H352OxQEous

Even though they are made for Shopify Google Tag Manager - Analytics integrations; you will still get how GTM works, processes the data and passes it into GA4.

Collapse
 
igorsmirnov_tw profile image
Igor Smirnov

For those who's dealing with GTM containers on regular basis, here is a helper app to visualize the container setup and also see all set dimensions, metrics and parameters of the core Google tags in a tabular view. Greatly helps in audit.
gtmutility.com

Collapse
 
khanakia profile image
Aman Bansal

What's the different between the Event Param and User Param ?
What difference will it make if i select any param either under event or user ?

Collapse
 
ekuplu profile image
Erman Küplü

Good catch!
Event parameters are event-based - like revenue. You may have a different revenue every time you make a purchase.

User parameters are based on user-like user ID. You'll still have the same user-ID in each event.