dataLayers & Google Tag Manager & GA4 for Developers
Tags: datalayer, googletagmanager, tutorial, ga4
Published: 2021-03-30 10:05:20

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](https://www.youtube.com/watch?v=XHDjkrXVgFU&t=3s&ab_channel=Analyzify-PowerfulShopifyAnalytics). 

Let's immediately jump into the example: 

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

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'
    }]
  }
});
```
If you want to see another example, you can check out [Analyzify Shopify DataLayers](https://analyzify.com/shopify-datalayer/). 

###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>
```

1st Step:
```
dataLayer.push({
			'event': 'signup-steps',
			'step': '1',
			'stepname' : 'GetStarted'
		});
```

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
		});
```

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
		});
```

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
		});
```

Final Step:
```
dataLayer.push({
			'event': 'signup-steps',
			'step': '9',
			'stepname' : 'ThankYou',
                        'uid': '12345',
                        'order-ID' :'order-ID'
		});
```

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](https://dev.to/analyzify/how-to-set-up-google-tag-manager-on-shopify-2021-tutorial-p19). 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/abkk23z94w2uprnmooiw.png)

Name the Trigger nicely, and choose CUSTOM EVENT from the Event Types: 
![GTM event types](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6vyqnyvfi3po7b71bngw.png)

Use the exact same name as you pushed into the dataLayer > 
![GTM custom event](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cx52nq79sk1das3x1knc.png)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mtp5yif4ng5qzjtbduya.png)
 
Make sure to use the exact same name as in the dataLayer: 
![GTM create custom variable](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0cwhvdpusxrhe6jtmght.png)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ota5k23ls5nttdl9qzxq.png)
 
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rxl9vii2v3rst3d0jek8.png)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xj5hp0nqjpdsp3ypfr9t.png)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tlbh0jgwfyuc4995eowu.png)
 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n3sva46elwconwqpeqse.png)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8msxne52wfyzrpscfrdz.png)
 
### 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gt2at4fsfrmxaf2kkhv1.png)
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](https://www.youtube.com/watch?v=h8o7CBqa-C4&t=3s&ab_channel=Analyzify-PowerfulShopifyAnalytics). 

Choose your configuration and name the event properly. 
![GA4 Event Tag - GTM - 2](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i1mn1uvfcim7wxj4e22q.png)
 
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fbkar0kb7piksc8pgfg5.png)
 
Make sure that it looks like this. The parameters name on the left and variable names on the right > 
![GTM - GA4 Custom Parameters - 2](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/l3133ad0x9o6ksa354u8.png)
 
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kfp6rap0leb7qx0amhkz.png)
 
And then choose the trigger you recently created > 
![GTM Tag Triggers 2](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/afg759sk4s3h915r5h8g.png)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5jdl2ngmfl6g4x0mg65p.gif)


## 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](https://analyzify.com/). 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](https://analyzify.com/exciting-features-google-analytics-4/) 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m4gu76f534xfkiat78k6.png)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wgs3gl4iigbt7thyd0au.png)
 
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.