Home / How to setup GA4 Shopify

How to setup GA4 Shopify

Setup GA4 on Shopify Complete Guide

The “setup GA4 Shopify” can be done in 3 ways that don’t require a monthly cost:

  1. Google Channel App.
  2. Ga4 is set up through Google Tag. Manager.
  3. GA4 setup using Google Tag.

You can find more about why you should set up GA4 for your business here.

How do you setup GA4 Shopify using the Google Channel App?

What do you need to setup GA4 Shopify using the Google Channel App?

  1. You need a GA4 account. (If you don’t have one, watch how to create one here.)
  2. You need a Google Tag Manager account. (If you don’t have one, watch how to create a GTM account here.)
  3. Shopify account. (if you are not the owner, you need access to install the app and the Google Analytics account admin permission.)

Let’s start with the setup GA4 Shopify using the Google Channel App.

You can follow the instructions or check the video.

Follow the below steps to set up GA4 in Shopify using the Google Channel App.

  1. In the Shopify dashboard, click on Apps from the left side menu.
  2. Now, in the bottom search menu, click on App and Sales Channel settings.
  3. Click the “Shopify App Store” button right after it opens.
  4. In the Shopify App Store, search for Google and YouTube and install the app. Or you can use this link: Google & YouTube.
  5. Click on the Add Sale channel and select the connected account.
  6. Click the “Connect Google account” button in the App setup window.
  7. Now select the Google account that is connected.
  8. Once connected, you’ll be introduced to the App setup window again. You have to complete all the checklist items from Google to get started. As shown in the video.
    • You’ll be required to remove the password from the online store if it hasn’t been removed already.
    • In the second checklist, you must add a refund policy and terms of service.
    • In the third checklist, you have to add your contact information.
  9. You can also connect your store with your existing Merchant account. You can create one from the option if you don’t have one.
  10. After completing the checklist, check the Terms and Conditions and click on Complete Setup.
  11. Now, toggle to the Overview tab in the same app and look for Google Analytics 4.
  12. Click on Get Started.
  13. Now, it will automatically fetch your GA4 account from the connected email that was selected previously.
  14. If you have multiple GA4 accounts, you can choose the correct one and click the “Connect” button.
  15. By this, you have successfully connected your GA4 to your Shopify store.
  16. To verify the connection, you can make a test purchase or any event and check the data sent to your GA4 account. 

Video on how to setup GA4 Shopify using the Google Channel App.

How to setup GA4 Shopify using Google Tag Manager?

What do you need to setup GA4 Shopify using Google Tag Manager?

  1. You need the ecommerce dataLayer to place in the theme and checkout codes.
  2. You need a Google Tag Manager account.
  3. Shopify account. (if you are not the owner, you need access to edit the theme code and checkout settings).
  4. Google Analytics account. (if not the owner, edit permission.)
  5. Some technical skill, if you don’t have the skill, some patience.

Let’s start with the setup GA4 Shopify using GTM.

Here is the process:

  1. Setup ecommerce datalayer.
  2. Setup GTM code on the website.
  3. Check if the ecommerce datalyer works.
  4. Collect the data within GTM and send it to GA4, trust, and verify.
  5. Publish.

Step 1. Setup the ecommerce datalayers.

Copy the ecommerce datalayer script below and follow the steps in this video.

<script>

if(!window.jQuery){
	var jqueryScript = document.createElement('script');
	jqueryScript.setAttribute('src','https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js');
	document.head.appendChild(jqueryScript);
}

__DL__jQueryinterval = setInterval(function(){
	// wait for jQuery to load & run script after jQuery has loaded
	if(window.jQuery){
    	// search parameters
    	getURLParams = function(name, url){
        	if (!url) url = window.location.href;
        	name = name.replace(/[\[\]]/g, "\\$&");
        	var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
        	results = regex.exec(url);
        	if (!results) return null;
        	if (!results[2]) return '';
        	return decodeURIComponent(results[2].replace(/\+/g, " "));
    	};
   	 
    	/**********************
    	* DYNAMIC DEPENDENCIES
    	***********************/
   	 
    	__DL__ = {
        	dynamicCart: true,  // if cart is dynamic (meaning no refresh on cart add) set to true
        	debug: false, // if true, console messages will be displayed
        	cart: null,
        	wishlist: null,
        	removeCart: null
    	};
   	 
    	customBindings = {
        	cartTriggers: [],
        	viewCart: [],
        	removeCartTrigger: [],
        	cartVisableSelector: [],
        	promoSubscriptionsSelectors: [],
        	promoSuccess: [],
        	ctaSelectors: [],
        	newsletterSelectors: [],
        	newsletterSuccess: [],
        	searchPage: [],
        	wishlistSelector: [],
        	removeWishlist: [],
        	wishlistPage: [],
        	searchTermQuery: [getURLParams('q')], // replace var with correct query
    	};
   	 
    	/* DO NOT EDIT */
    	defaultBindings = {
        	cartTriggers: ['form[action="/cart/add"] [type="submit"],.add-to-cart,.cart-btn'],
        	viewCart: ['form[action="/cart"],.my-cart,.trigger-cart,#mobileCart'],
        	removeCartTrigger: ['[href*="/cart/change"]'],
        	cartVisableSelector: ['.inlinecart.is-active,.inline-cart.is-active'],
        	promoSubscriptionsSelectors: [],
        	promoSuccess: [],
        	ctaSelectors: [],
        	newsletterSelectors: ['input.contact_email'],
        	newsletterSuccess: ['.success_message'],
        	searchPage: ['search'],
        	wishlistSelector: [],
        	removeWishlist: [],
        	wishlistPage: []
    	};
   	 
    	// stitch bindings
    	objectArray = customBindings;
    	outputObject = __DL__;
   	 
    	applyBindings = function(objectArray, outputObject){
        	for (var x in objectArray) {  
            	var key = x;
            	var objs = objectArray[x];
            	values = [];    
            	if(objs.length > 0){    
                	values.push(objs);
                	if(key in outputObject){         	 
                    	values.push(outputObject[key]);
                    	outputObject[key] = values.join(", ");
                	}else{   	 
                    	outputObject[key] = values.join(", ");
                	}   
            	}  
        	}
    	};
   	 
    	applyBindings(customBindings, __DL__);
    	applyBindings(defaultBindings, __DL__);
   	 
    	/**********************
    	* PREREQUISITE LIBRARIES
    	***********************/
   	 
    	clearInterval(__DL__jQueryinterval);
   	 
    	// jquery-cookies.js
    	if(typeof $.cookie!==undefined){
        	(function(a){if(typeof define==='function'&&define.amd){define(['jquery'],a)}else if(typeof exports==='object'){module.exports=a(require('jquery'))}else{a(jQuery)}}(function($){var g=/\+/g;function encode(s){return h.raw?s:encodeURIComponent(s)}function decode(s){return h.raw?s:decodeURIComponent(s)}function stringifyCookieValue(a){return encode(h.json?JSON.stringify(a):String(a))}function parseCookieValue(s){if(s.indexOf('"')===0){s=s.slice(1,-1).replace(/\\"/g,'"').replace(/\\\\/g,'\\')}try{s=decodeURIComponent(s.replace(g,' '));return h.json?JSON.parse(s):s}catch(e){}}function read(s,a){var b=h.raw?s:parseCookieValue(s);return $.isFunction(a)?a(b):b}var h=$.cookie=function(a,b,c){if(arguments.length>1&&!$.isFunction(b)){c=$.extend({},h.defaults,c);if(typeof c.expires==='number'){var d=c.expires,t=c.expires=new Date();t.setMilliseconds(t.getMilliseconds()+d*864e+5)}return(document.cookie=[encode(a),'=',stringifyCookieValue(b),c.expires?'; expires='+c.expires.toUTCString():'',c.path?'; path='+c.path:'',c.domain?'; domain='+c.domain:'',c.secure?'; secure':''].join(''))}var e=a?undefined:{},cookies=document.cookie?document.cookie.split('; '):[],i=0,l=cookies.length;for(;i<l;i++){var f=cookies[i].split('='),name=decode(f.shift()),cookie=f.join('=');if(a===name){e=read(cookie,b);break}if(!a&&(cookie=read(cookie))!==undefined){e[name]=cookie}}return e};h.defaults={};$.removeCookie=function(a,b){$.cookie(a,'',$.extend({},b,{expires:-1}));return!$.cookie(a)}}))}
   	 
    	/**********************
    	* Begin dataLayer Build
    	***********************/
   	 
    	window.dataLayer = window.dataLayer || [];  // init data layer if doesn't already exist

    	var template = "{{template}}";
   	 
    	/**
    	* Landing Page Cookie
    	* 1. Detect if user just landed on the site
    	* 2. Only fires if Page Title matches website */
   	 
    	$.cookie.raw = true;
    	if ($.cookie('landingPage') === undefined || $.cookie('landingPage').length === 0) {
        	var landingPage = true;
        	$.cookie('landingPage', unescape);
        	$.removeCookie('landingPage', {path: '/'});
        	$.cookie('landingPage', 'landed', {path: '/'});
    	} else {
        	var landingPage = false;
        	$.cookie('landingPage', unescape);
        	$.removeCookie('landingPage', {path: '/'});
        	$.cookie('landingPage', 'refresh', {path: '/'});
    	}
    	if (__DL__.debug) {
        	console.log('Landing Page: ' + landingPage);
    	}
   	 
    	/**
    	* Log State Cookie */
   	 
    	{% if customer %}
    	var isLoggedIn = true;
    	{% else %}
    	var isLoggedIn = false;
    	{% endif %}
    	if (!isLoggedIn) {
        	$.cookie('logState', unescape);
        	$.removeCookie('logState', {path: '/'});
        	$.cookie('logState', 'loggedOut', {path: '/'});
    	} else {
        	if ($.cookie('logState') === 'loggedOut' || $.cookie('logState') === undefined) {
            	$.cookie('logState', unescape);
            	$.removeCookie('logState', {path: '/'});
            	$.cookie('logState', 'firstLog', {path: '/'});
        	} else if ($.cookie('logState') === 'firstLog') {
            	$.cookie('logState', unescape);
            	$.removeCookie('logState', {path: '/'});
            	$.cookie('logState', 'refresh', {path: '/'});
        	}
    	}
   	 
    	if ($.cookie('logState') === 'firstLog') {
        	var firstLog = true;
    	} else {
        	var firstLog = false;
    	}
   	 
    	/**********************
    	* DATALAYER SECTIONS
    	***********************/
   	 
    	/**
    	* DATALAYER: Landing Page
    	* Fires any time a user first lands on the site. */
   	 
    	if ($.cookie('landingPage') === 'landed') {
        	dataLayer.push({
            	'pageType': 'Landing',
            	'event': 'first_time_visitor'
        	});
    	}
   	 
    	/**
    	* DATALAYER: Log State
    	* 1. Determine if user is logged in or not.
    	* 2. Return User specific data. */
   	 
    	var logState = {
        	{% if shop.customer_accounts_enabled %}
        	{% if customer %}
        	'userId'    	: {{customer.id | json}},
        	'customerEmail' : {{customer.email | json}},
        	'logState'  	: "Logged In",
        	'customerInfo'  : {
            	'firstName'   : {{customer_address.first_name | json}},
            	'lastName'	: {{customer_address.last_name | json}},
            	'address1'	: {{customer_address.address1 | json}},
            	'address2'	: {{customer_address.address2 | json}},
            	'street'  	: {{customer_address.street | json}},
            	'city'    	: {{customer_address.city | json}},
            	'province'	: {{customer_address.province | json}},
            	'zip'     	: {{customer_address.zip | json}},
            	'country' 	: {{customer_address.country | json}},
            	'phone'   	: {{customer_address.phone | json}},
            	'totalOrders' : {{customer.orders_count | json}},
            	'totalSpent'  : {{customer.total_spent | money_without_currency | remove: "," | json}}
        	},
        	{% else %}
        	'logState' : "Logged Out",
        	{% endif %}
        	{% endif %}
        	'firstLog'  	: firstLog,
        	'customerEmail' : {{customer.email | json}},
        	'timestamp' 	: Date().replace(/\(.*?\)/g,''),  
        	{% if customer.orders_count > 2 %}
        	'customerType'   	: 'Returning',
        	'customerTypeNumber' : '0',
        	{% else %}
        	'customerType'   	: 'New',
        	'customerTypeNumber' :'1',
        	{% endif %}
        	'shippingInfo' : {
            	'fullName'  : {{checkout.shipping_address.name | json}},
            	'firstName' : {{checkout.shipping_address.first_name | json}},
            	'lastName'  : {{checkout.shipping_address.last_name | json}},
            	'address1'  : {{checkout.shipping_address.address1 | json}},
            	'address2'  : {{checkout.shipping_address.address2 | json}},
            	'street'	: {{checkout.shipping_address.street | json}},
            	'city'  	: {{checkout.shipping_address.city | json}},
            	'province'  : {{checkout.shipping_address.province | json}},
            	'zip'   	: {{checkout.shipping_address.zip | json}},
            	'country'   : {{checkout.shipping_address.country | json}},
            	'phone' 	: {{checkout.shipping_address.phone | json}},
        	},
        	'billingInfo' : {
            	'fullName'  : {{checkout.billing_address.name | json}},
            	'firstName' : {{checkout.billing_address.first_name | json}},
            	'lastName'  : {{checkout.billing_address.last_name | json}},
            	'address1'  : {{checkout.billing_address.address1 | json}},
            	'address2'  : {{checkout.billing_address.address2 | json}},
            	'street'	: {{checkout.billing_address.street | json}},
            	'city'  	: {{checkout.billing_address.city | json}},
            	'province'  : {{checkout.billing_address.province | json}},
            	'zip'   	: {{checkout.billing_address.zip | json}},
            	'country'   : {{checkout.billing_address.country | json}},
            	'phone' 	: {{checkout.billing_address.phone | json}},
        	},
        	'checkoutEmail' : {{checkout.email | json}},
        	'currency'  	: {{shop.currency | json}},
        	'pageType'  	: 'Log State',
        	'event'     	: 'logState'
    	}
    	dataLayer.push(logState);
    	/**
    	* DATALAYER: Homepage */
   	 
    	if(document.location.pathname == "/"){
        	dataLayer.push({
            	'pageType' : 'Homepage',
            	'event'	: 'homepage',
            	logState
        	});
    	}
    	/**
    	* DATALAYER: 404 Pages
    	* Fire on 404 Pages */
 		 {% if template contains '404' %}
        	dataLayer.push({
            	'event':'404',
            	'page': window.location.pathname
        	});
 		 {% endif %}
    	/**
    	* DATALAYER: Blog Articles
    	* Fire on Blog Article Pages */
    	{% if template contains 'article' %}
        	dataLayer.push({
            	'author'  	: {{article.author | json}},
            	'title'   	: {{article.title | json}},
            	'dateCreated' : {{article.created_at | json}},
            	'pageType'	: 'Blog',
            	'event'   	: 'blog'
        	});
    	{% endif %}
   	 
    	/** DATALAYER: Product List Page (Collections, Category)
    	* Fire on all product listing pages. */
    	{% if template contains 'collection' %}
        	var ecommerce = {
            	'items': [
                	{% for product in collection.products %}{
                    	'item_id'    	: {{product.id | json}},             	 
                    	'item_variant'	: {{product.selected_or_first_available_variant.id | json}},        	 
                    	'item_name'  	: {{product.title | json}},
                    	'price'       	: {{product.price | money_without_currency | replace: ',', '.' | json}},
                    	'item_brand'  	: {{product.vendor | json}},
                    	'item_category'   : {{product.type | json}},
                    	'item_list_name'  : {{collection.title | json}},
                    	'imageURL'    	: "https:{{product.featured_image.src|img_url:'grande'}}",
                    	'productURL'  	: '{{shop.secure_url}}{{product.url}}',
                    	'sku'         	: {{product.selected_variant.sku | json}},
                	},
                	{% endfor %}]
            	};  
        	dataLayer.push({
            	'productList' : {{collection.title | json}},
            	'pageType'	: 'Collection',
            	'event'   	: 'view_item_list',
            	ecommerce
        	});
    	{% endif %}
       	 
    	/** DATALAYER: Product Page
    	* Fire on all Product View pages. */
    	{% if template contains 'product' %}  
        	var ecommerce = {
            	'items': [{
                	'item_id'    	: {{product.id | json}},  
                	'item_variant'	: {{product.selected_or_first_available_variant.id | json}},        	 
                	'item_name'  	: {{product.title | json}},
                	'price'       	: {{product.price | money_without_currency | replace: ',', '.' | json}},
                	'item_brand'  	: {{product.vendor | json}},
                	'item_category'   : {{product.type | json}},
                	'item_list_name'  : {{collection.title | json}},
                	'description' 	: {{product.description | strip_newlines | strip_html | json}},
                	'imageURL'    	: 'https:{{product.featured_image.src|img_url:'grande'}}',
                	'productURL'  	: '{{product.url}}'
            	}]
        	};          	 
        	dataLayer.push({
            	'pageType' : 'Product',
            	'event'	: 'view_item',
       		  ecommerce
       		 });
        	$(__DL__.cartTriggers).click(function(){
   			 dataLayer.push({               	 
                	'event'	: 'add_to_cart',
                	ecommerce
          		 });             	 
        	});         	 
     	 {% endif %}
    	/** DATALAYER: Cart View
    	* Fire anytime a user views their cart (non-dynamic) */          	 
    	{% if template contains 'cart' %}
        	var ecommerce = {
            	'currency': {{cart.currency.iso_code | json}},
            	'value': {{cart.total_price | divided_by: 100.0 | json}},
            	'items':[{% for line_item in cart.items %}{
                	'item_id'    	: {{line_item.product.id | json}},             	 
                	'item_variant'	: {{product.selected_or_first_available_variant.id | json}},        	 
                	'item_name'  	: {{line_item.product.title | json}},
                	'price'       	: {{line_item.product.price | money_without_currency | replace: ',', '.' | json}},
                	'item_brand'  	: {{line_item.product.vendor | json}},
                	'item_category'   : {{line_item.product.type | json}},
                	'item_list_name'  : {{line_item.collection.title | json}},
                	'quantity'    	: {{line_item.quantity | json}},
                	'discount'   	   : {{discount.code | json}}
            	},{% endfor %}],
        	};
        	dataLayer.push({
            	'pageType' : 'Cart',
            	'event'	: 'view_cart',
            	ecommerce
        	});
    	{% endif %}
           	 
    	/** DATALAYER: Checkout on Shopify Plus **/
    	if(Shopify.Checkout){
        	var ecommerce = {
            	'transaction_id': '{{checkout.order_number  | json}}',
            	'affiliation': {{shop.name | json}},
            	'value': {{checkout.total_price | money_without_currency | replace: ',', '.' | json}},
            	'tax': {{checkout.tax_price | money_without_currency | replace: ',','.' | json}},
            	'shipping': {{checkout.shipping_price | money_without_currency | replace: ',','.' | json}},
            	'subtotal': {{checkout.subtotal_price | money_without_currency| replace: ',','.' | json}},
            	'currency': {{checkout.currency | json}},
            	{% for discount in checkout.discounts %}
            	'coupon': {{discount.code | json}},
            	'discount'  : {{discount.amount | money_without_currency | json}},
            	{% endfor %}
            	'email': {{checkout.email | json}},
            	'items':[{% for line_item in checkout.line_items %}{
                	'item_id'    	: {{line_item.product.id | json}},             	 
                	'item_variant'	: {{product.selected_or_first_available_variant.id | json}},        	 
                	'item_name'  	: {{line_item.product.title | json}},
                	'price'       	: {{line_item.product.price | money_without_currency | replace: ',', '.' | json}},
                	'item_brand'  	: {{line_item.product.vendor | json}},
                	'item_category'   : {{line_item.product.type | json}},
                	'item_list_name'  : {{line_item.collection.title | json}},
                	'quantity'    	: {{line_item.quantity | json}},
                	'discount'   	   : {{discount.code | json}}
                	},{% endfor %}],
            	};
        	if(Shopify.Checkout.step){
            	if(Shopify.Checkout.step.length > 0){
                	if (Shopify.Checkout.step === 'contact_information'){
                    	dataLayer.push({
                        	'event'	:'begin_checkout',
                        	'pageType' :'Customer Information',
                        	'step': 1,
                   		 ecommerce
                    	});
                	}else if (Shopify.Checkout.step === 'shipping_method'){
                    	dataLayer.push({
                        	'event'	:'add_shipping_info',
                        	'pageType' :'Shipping Information',
                        	ecommerce
                    	});
                	}else if( Shopify.Checkout.step === "payment_method" ){
                    	dataLayer.push({
                        	'event'	:'add_payment_info',
                        	'pageType' :'Add Payment Info',
                   		 ecommerce
                    	});
                	}
            	}
                       	 
            	/** DATALAYER: Transaction */
            	if(Shopify.Checkout.page == "thank_you"){
                	dataLayer.push({
                	'pageType' :'Transaction',
                	'event'	:'purchase',
                	ecommerce
                	});
            	}          	 
        	}
    	}
         	 
    	/** DOM Ready **/    
    	$(document).ready(function() {
        	/** DATALAYER: Search Results */
        	var searchPage = new RegExp(__DL__.searchPage, "g");
        	if(document.location.pathname.match(searchPage)){
            	var ecommerce = {
                	items :[{% for product in search.results %}{
                    	'item_id'    	: {{product.id | json}},             	 
                    	'item_variant'	: {{product.selected_or_first_available_variant.id | json}},        	 
                    	'item_name'  	: {{product.title | json}},
                    	'price'       	: {{product.price | money_without_currency | replace: ',', '.' | json}},
                    	'item_brand'  	: {{product.vendor | json}},
                    	'item_category'   : {{product.type | json}},
                    	'item_list_name'  : {{product.collection.title | json}},
                	},{% endfor %}],
            	};
            	dataLayer.push({
                	'pageType'   : "Search",
                	'search_term' : __DL__.searchTermQuery,                                  	 
                	'event'  	: "search",
                	'item_list_name'  : {{line_item.collection.title | json}},
                	ecommerce
            	});    
        	}
       	 
        	/** DATALAYER: Remove From Cart **/
        	{% if template contains 'cart' %}
            	var ecommerce = {
                	'items':[{% for line_item in cart.items %}{
                    	'item_id'    	: {{line_item.product.id | json}},             	 
                    	'item_variant'	: {{product.selected_or_first_available_variant.id | json}},        	 
                    	'item_name'  	: {{line_item.product.title | json}},
                    	'price'       	: {{line_item.product.price | money_without_currency | replace: ',', '.' | json}},
                    	'item_brand'  	: {{line_item.product.vendor | json}},
                    	'item_category'   : {{line_item.product.type | json}},
                    	'item_list_name'  : {{line_item.collection.title | json}},
                    	'quantity'    	: {{line_item.quantity | json}},
                    	'discount'   	   : {{discount.code | json}}
                	},{% endfor %}],
            	};
           	 
            	$(__DL__.removeCartTrigger).click(function(){
                	dataLayer.push({
                    	'pageType'   : "Remove from cart",
                    	'event' : 'remove_from_cart',
                    	ecommerce
                	});                            	 
            	});          	 
        	{% endif %}

        	/** Google Tag Manager **/
        	(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
        	new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
        	j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
        	'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
        	})(window,document,'script','dataLayer','GTM-AAAAAAA');

    	}); // document ready
	}
}, 500);
</script>

After you copy and paste the ecommerce data layer above, you need to go to theme.liquid and copy and paste this {% include 'ecommerce-dataLayer-all-pages' %} right below the <head>.

This is the purchase ecommerce datalayer you need to place the checkout settings order status section: (check steps in video)

<script>
{% if first_time_accessed %}
window.dataLayer = window.dataLayer || [];
dataLayer.push({
 event: 'purchase',
 checkoutEmail: '{{ checkout.email }}',
 fullName: '{{ checkout.billing_address.name }}',  
 firstName: '{{ checkout.billing_address.first_name }}',  
 lastName: '{{ checkout.billing_address.last_name }}',  
 address1: '{{ checkout.billing_address.address1 }}',  
 address2: '{{ checkout.billing_address.address2 }}',  
 street: '{{ checkout.billing_address.street }}',  
 city: '{{ checkout.billing_address.city }}',  
 province: '{{ checkout.billing_aaddress.province_code }}',  
 zip: '{{ checkout.billing_address.zip }}',  
 country: '{{ checkout.billing_address.country_code }}',  
 phone: '{{ checkout.billing_address.phone }}', 
 ecommerce:{
 currency: '{{ checkout.currency }}',
 value: {{total_price | times: 0.01}},
 transaction_id: '{{order_number}}',
 tax: {{tax_price | times: 0.01}},
 shipping: {{shipping_price | times: 0.01}},
 affiliation: '{{ shop.domain }}',
 items: [
         {% for line_item in line_items %}{
         item_id: '{{line_item.product_id}}',
         item_name: '{{line_item.title}}',
         quantity: {{line_item.quantity}},
         price: {{line_item.original_price | times: 0.01}}
         },{% endfor %}
         ]
 }
 });
 {% endif %}
</script>

This is the begin checkout ecommerce datalayer you need to use for the checkout button: (check steps in video)

onclick="dataLayer.push({  
  	event: 'begin_checkout',
    ecommerce:{
    value: {{ cart.total_price | times: 0.01 }}, 
    currency: '{{ cart.currency.iso_code }}', 
    items: [
         {% for line_item in cart.items %}{
         item_id: '{{line_item.product_id}}',
         item_name: '{{line_item.title}}',
         quantity: {{line_item.quantity}},
         price: {{line_item.original_price | times: 0.01}}
         },{% endfor %}
         ]
}
});"

Follow these instructions to set up GA4 in Shopify using GTM. (Or check video)

  1. You have to copy the first Datalayer from the article.
  2. Go to your Shopify dashboard.
  3. Click on Online Store from the left side menu. If you can’t find it, click on the Sales channel, and you’ll find the Online Store.
  4. Now click on the three dots menu beside your current theme section, and from the drop-down, click on Edit code.
  5. Now, search for the Snippets folder in the files menu, and click on Add a new snippet.
  6. Name the new Snippet “ecommerce-dataLayer-all-pages” and paste the copied code here.
  7. Click on save.
  8. Now, open the theme.liquid from the left side menu on the same page.
  9. In the code, paste this “{% include 'ecommerce-dataLayer-all-pages' %}” as high as possible.
  10. Click on save.
  11. Go to your Shopify settings from your dashboard in the bottom left corner.
  12. Now click on checkout, and in the checkout settings, paste the Purchase E-commerce Datalayer code from the article in the Additional Scripts section.
  13. Click on save.
  14. Again, go to your theme code, as explained in Step 4.
  15. This item may be a little tricky to find because it might depend from theme to theme. So we are looking for cart-notification.liquid in our case.
  16. Now, within cart-notification.liquid find the checkout button code to be a specific button class. After the “name=”checkout” paste, the checkout e-commerce data layer code from the article begins.
  17. Click on save.
  18. Now search for main-cart-footer.liquid and the code finds the checkout button code to be a specific button class. After the “name=”checkout” paste again the begin checkout e-commerce data layer code from the article.
  19. Click on save.
  20. Go to your Google Tag Manager dashboard and copy your GTM ID. 
  21. Go back to your theme code and open the ecommerce-dataLayer-all-pages file.
  22. Now search for “GTM-AAAAAAA” and replace it with your GTM ID.
  23. Click on save.
  24. Now, go to your theme.liquid In the Body section, paste the GTM body code. (found in the GTM dashboard by clicking on the GTM ID)
  25. Click on save.
  26. Copy the head code from the GTM dashboard by clicking on GTM ID.
  27. Open settings in your Shopify dashboard from the bottom left side.
  28. Click checkout and paste it in the Additional Scripts below the data layer pasted previously. 
  29. Click on save.
  30. Now, Let’s tag for Google Tag Manager.
  31. Go to your GTM dashboard and create a new tag.
  32. Click on Tag Configuration, choose Google Analytics, and click Google Tag.
  33. Now, paste your GA4 ID in the Tag ID field. You can copy your GA4 ID from your GA4 dashboard by searching for the term “tracking ID.”
  34. Click on triggers and select All Pages.
  35. Now, name the tag. We like to call it G-Tag-GA-4-config-pageview-allpages.
  36. Click on save.
  37. Let’s create the second tag. Click on New
  38. Click on Tag Configuration, choose Google Analytics, and click on Google Analytics: GA4 Event.
  39. Now, paste your GA-4 ID in the Measurement ID field.
  40. Name the event as view_item in the event name field.
  41. Create a trigger by clicking on the trigger section.
  42. Now, click on the + icon. In trigger configuration, choose Custom Event.
  43. In the event name field, type “view_item” 
  44. Name the trigger as E-view_item. However, you can name the trigger as you like.
  45. Save the trigger.
  46. Again, in the tag setup, click on Event Parameters and click on Add parameter.
  47. The first parameter is value. So, in the event parameter name, write “value”.
  48. Now, In the value section beside the event parameter name, click on the small icon in the field, click on the + icon, then click on Variable Configuration, and choose Data Layer Variable. Now, in the Data Layer Variable Name, you have to write the structure to locate the value from the Data Layer code on the website. In this case, it is “ecommerce.items.0.price”. Now name the variable “dlv-ecommerce.items.0.price” and click on save.
  49. The following parameter is currency. So, in the event parameter name, write “currency”.
  50. Now, in the value section beside the event parameter name, follow the exact instructions from Step 48 for creating the variable. In the Data Layer Variable Name, write “currency”. Now name the variable “dlv-currency” and click on save.
  51. The following parameter is items. So, in the event parameter name, write “items”.
  52. Now, in the value section beside the event parameter name, follow the exact instructions from Step 48 for creating the variable. In the Data Layer Variable Name, write “ecommerce.items”. Now name the variable “dlv-ecommerce.items” and click on save.
  53. Now, name the tag “GA-4-view_item” and save the tag.
  54. Let’s create the following tag.
  55. Click on New, then Tag Configuration, choose Google Analytics and click on Google Analytics: GA4 Event.
  56. Now, paste your GA-4 ID in the Measurement ID field.
  57. Name the event view_item_list in the event name field.
  58. Create a trigger by clicking on the trigger section.
  59. Now, click on the + icon. In trigger configuration, choose Custom Event.
  60. In the event name field, type “view_item_list.” Name the trigger as E-view_item_list.
  61. Save the trigger.
  62. Again, in the tag setup, click on Event Parameters and click on Add parameter.
  63. In the Event Parameter Name, write “items“, and in the Value field beside it, type “{{“ items, and you’ll see the already saved variables, choose {{dlv-ecommerce.items}}.
  64. Name the tag as GA-4-view_item_list and click on save.
  65. Let’s create the following tag, which is Add to Cart.
  66. Click on New, then click on Tag Configuration, choose Google Analytics, and click on Google Analytics: GA4 Event.
  67. Now, paste your GA-4 ID in the Measurement ID field.
  68. Name the event add_to_cart in the event name field.
  69. Create a trigger by clicking on the trigger section.
  70. Now, click on the + icon. In trigger configuration, choose Custom Event.
  71. In the event name field, type “add_to_cart.” 
  72. Name the trigger as E-add_to_cart.
  73. Save the trigger.
  74. Again, in the tag setup, click on Event Parameters and click on Add parameter.
  75. The first parameter is value. So, in the event parameter name, write “value,” and in the Value field beside it, type “{{“ items, and you’ll see the already saved variables, choose {{dlv-ecommerce.items.0.price}}.
  76. The following parameter is currency. So, in the event parameter name, write “currency,” and in the Value field beside it, type “{{“ items, and you’ll see the already saved variables. Choose {{dlv-currency}}.
  77. The following parameter is items. So, in the event parameter name, write “items,” and in the Value field beside it, type “{{“ items, and you’ll see the already saved variables, choose {{dlv-ecommerce.items}}. Now save the tag.
  78. Let’s create the following tag, which is Begin Checkout.
  79. Click on New, then click on Tag Configuration, choose Google Analytics, and click on Google Analytics: GA4 Event.
  80. Now, paste your GA-4 ID in the Measurement ID field.
  81. Name the event as begin_checkout in the event name field.
  82. Create a trigger by clicking on the trigger section.
  83. Now, click on the + icon. In trigger configuration, choose Custom Event.
  84. In the event name field, type “begin_checkout.
  85. Name the trigger as E-begin_checkout.
  86. Save the trigger.
  87. Again, in the tag setup, click on Event Parameters and click on Add parameter.
  88. The first parameter is value. So, in the event parameter name, write “value”.
  89. Now, in the value section beside the event parameter name, follow the exact instructions from Step 48 for creating the variable. In the Data Layer Variable Name, write “ecommerce.value”. Now name the variable “dlv-ecommerce.value” and click on save.
  90. The following parameter is currency. So, in the event parameter name, write “currency,” and in the Value field beside it, type “{{“ items, and you’ll see the already saved variables, choose {{dlv-currency}}.
  91. The following parameter is items. So, in the event parameter name, write “items,” and in the Value field beside it, type “{{“ items, and you’ll see the already saved variables, choose {{dlv-ecommerce.items}}.
  92. Click on save.
  93. Let’s create the following tag, which is Purchase.
  94. Click on New, then Tag Configuration, choose Google Analytics and click on Google Analytics: GA4 Event.
  95. Now, paste your GA-4 ID in the Measurement ID field.
  96. Name the event as purchase in the event name field.
  97. Create a trigger by clicking on the trigger section.
  98. Now, click on the + icon. In trigger configuration, choose Custom Event.
  99. In the event name field, type “purchase.”
  100. Name the trigger as E-purchase.
  101. Save the trigger.
  102. Again, in the tag setup, click on Event Parameters and click on Add parameter.
  103. The first parameter is value. So, in the event parameter name, write “value,” and in the Value field beside it, type “{{“ items, and you’ll see the already saved variables, choose {{dlv-ecommerce.value}}.
  104. The following parameter is currency. So, in the event parameter name, write “currency.”
  105. Now, in the value section beside the event parameter name, follow the exact instructions from Step 48 for creating the variable. In the Data Layer Variable Name, write “ecommerce.currency”. Now name the variable “dlv-ecommerce.currency” and click on save.
  106. The following parameter is items. So, in the event parameter name, write “items,” and in the Value field beside it, type “{{“ items, and you’ll see the already saved variables, choose {{dlv-ecommerce.items}}.
  107. The following parameter is transaction ID. So, in the event parameter name, write “transaction_id”.
  108. Now, in the value section beside the event parameter name, follow the exact instructions from Step 48 for creating the variable. In the Data Layer Variable Name, write “ecommerce.transaction_id”. Now name the variable “dlv-ecommerce.transaction_id” and click on save.
  109. The following parameter is Affiliation. So, in the event parameter name, write “affiliation”.
  110. Now, in the value section beside the event parameter name, follow the exact instructions from Step 48 for creating the variable. In the Data Layer Variable Name, write “ecommerce.affiliation”. Now name the variable “dlv-ecommerce.affiliation” and click on save.
  111. The following parameter is Shipping. So, in the event parameter name, write “shipping”.
  112. Now, in the value section beside the event parameter name, follow the exact instructions from Step 48 for creating the variable. In the Data Layer Variable Name, write “ecommerce.shipping”. Now name the variable “dlv-ecommerce.shipping” and click on save.
  113. The last parameter is Tax. So, in the event parameter name, write “tax”.
  114. Now, in the value section beside the event parameter name, follow the exact instructions from Step 48 for creating the variable. In the Data Layer Variable Name, write “ecommerce.tax”. Now name the variable “dlv-ecommerce.tax” and click on save.
  115. Now, save the tag.
  116. Let’s create our last tag, which is View Cart.
  117. Click on New, then click on Tag Configuration, choose Google Analytics, and click on Google Analytics: GA4 Event.
  118. Now, paste your GA-4 ID in the Measurement ID field.
  119. Name the event as view_cart in the event name field.
  120. Create a trigger by clicking on the trigger section.
  121. Now, click on the + icon. In trigger configuration, choose Custom Event.
  122. In the event name field, type “view_cart.”
  123. Name the trigger as E-view_cart.
  124. Save the trigger.
  125. Again, in the tag setup, click on Event Parameters and click on Add parameter.
  126. The first parameter is value. So, in the event parameter name, write “value” and in the Value field beside it, type “{{“ items, and you’ll see the already saved variables, choose {{dlv-ecommerce.value}}.
  127. The following parameter is currency. So, in the event parameter name, write “currency,” and in the Value field beside it, type “{{“ items, and you’ll see the already saved variables, choose {{dlv-ecommerce.currency}}.
  128. The following parameter is items. So, in the event parameter name, write “items,” and in the Value field beside it, type “{{“ items, and you’ll see the already saved variables, choose {{dlv-ecommerce.items}}.
  129. Now, name the tag “GA-4-view_cart” and click on save.
  130. To test all the tags, click the Preview button on your GTM dashboard and make a test purchase to verify whether all tags work.

Video on how to set up Google Analytics 4 Shopify using Google Tag Manager?

How do you set up GA4 Shopify using Google Tag?

What do you need to set up GA4 Shopify using Google Tag?

  1. Google Tag code. Find them here.
  2. Shopify account. (if you are not the owner, you need access to edit the theme code and also access to the checkout settings)
  3. Google Analytics account. (if not the owner, edit permission.)
  4. Some technical skill, if you don’t have the skill, some patience.

Let us start with the implementation.

Here are the codes you need: (check the video)

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

Change ‘Tag_ID’ with your ‘G-XXXXXXXXXX’.

The view item list code:

<script>
gtag("event", "view_item_list", {
  item_list_id: "{{ collection.id | json }}",
  item_list_name: "{{collection.title | json}}",
  items: [
                {% for product in collection.products %}{
                  item_id: {{product.id}},
                  item_name: '{{product.title}}',
                  price: {{product.price | times: 0.01}},
                  item_brand: '{{ shop.name }}',
                  item_category: '{{ collection.title }}'
                },
                {% endfor %}]
});
</script>

The view item code:

<script>
gtag("event", "view_item", {
  currency: '{{ shop.currency }}',
  value: {{ product.price | times: 0.01 }},
  items: [{
           item_id: {{ product.id }},
           item_name: '{{ product.title }}',
           price: {{ product.price | times: 0.01 }},
           item_brand: '{{ shop.name }}',
           item_category: '{{ collection.title }}'
           }]
});
</script>

The add to cart code:

onclick=" gtag('event', 'add_to_cart', {
  currency: '{{ shop.currency }}',
  value: {{ product.price | times: 0.01 }},
  items: [{
           item_id: {{ product.id }},
           item_name: '{{ product.title }}',
           price: {{ product.price | times: 0.01 }},
           item_brand: '{{ shop.name }}',
           item_category: '{{ collection.title }}'
           }]
});"

The view cart code:

<script>
gtag("event", "view_cart", {
    value: {{ cart.total_price | times: 0.01 }}, 
    currency: '{{ cart.currency.iso_code }}', 
    items: [
         {% for line_item in cart.items %}{
         item_id: '{{line_item.product_id}}',
         item_name: '{{line_item.title}}',
         quantity: {{line_item.quantity}},
         price: {{line_item.original_price | times: 0.01}}
         },{% endfor %}
         ]
});
</script>

The Begin checkout code:

onclick=" gtag('event', 'begin_checkout', {
  value: {{ cart.total_price | times: 0.01 }}, 
    currency: '{{ cart.currency.iso_code }}', 
    items: [
         {% for line_item in cart.items %}{
         item_id: '{{line_item.product_id}}',
         item_name: '{{line_item.title}}',
         quantity: {{line_item.quantity}},
         price: {{line_item.original_price | times: 0.01}}
         },{% endfor %}
         ]
});"

The Purchase code:

<script>
gtag("event", "purchase", {
    transaction_id: '{{order_number}}',
    value: {{total_price | times: 0.01}},
    tax: {{tax_price | times: 0.01}},
    shipping: {{shipping_price | times: 0.01}},
    currency: '{{ checkout.currency }}',
    coupon: '{{ discount.code }}',
    affiliation: '{{ shop.domain }}',
    items: [
         {% for line_item in line_items %}{
         item_id: '{{line_item.product_id}}',
         item_name: '{{line_item.title}}',
         quantity: {{line_item.quantity}},
         price: {{line_item.original_price | times: 0.01}}
         },{% endfor %}
         ]
});
</script>

Follow the below instructions to set up GA4 on Shopify using Google Tag (or check the video)

  1. Firstly, we need to set up the GA4 global site tag.
  2. Go to your Google Analytics dashboard, and click on Admin (Settings Icon) from the button on the left side.
  3. In your property menu, click on Data Streams, then click on the website/property.
  4. In the Web Stream details page, scroll down and click on Configure tag settings.
  5. In Configure tag settings, click on the button that says, “Installation instructions.”
  6. Now, click on Install manually and copy the code.
  7. Go to your Shopify dashboard.
  8. Click on Online Store from the left side menu. If you can’t find it, click on the Sales channel to see the Online Store.
  9. Now click on the three dots menu beside your current theme section, and from the drop-down, click on Edit code.
  10. Open, now search for </head>. Directly paste the copied code right above the closing head tag.
  11. Click on save.
  12. Back to the Shopify dashboard, click on Settings from the button on the left side.
  13. In the settings menu, click Checkout and scroll until you find the Order status page. Underneath this, paste the code again in the Additional script.
  14. Click on save.
  15. Let’s implement our first code, the View Item List code. Go back to the article and copy the View Item List code.
  16. Go to your Shopify dashboard.
  17. Click on Online Store from the left side menu. If you can’t find it, click on Sales channel, and you’ll find the Online Store.
  18. Now click on the three dots menu beside your current theme section, and from the drop-down, click on Edit code.
  19. Search for main-collection-product-grid.liquid. You should find it in the Sections drop-down menu on the left side.
  20. In the main-collection-product-grid.liquid, paste the copied code above the “{%- if section….. %}” 
  21. Click on save.
  22. Let’s move on to implementing our View Item code. Go back to the article and copy the View Item code.
  23. Go to your Shopify dashboard.
  24. Click on Online Store from the left side menu. If you can’t find it, click on the Sales channel, and you’ll find the Online Store.
  25. Now click on the three dots menu beside your current theme section, and from the drop-down, click on Edit code.
  26. Search for main-product.liquid. You should find it in the Sections drop-down menu on the left side. 
  27. In main-product.liquid, right after the section code’s closing tag “<section    >” paste the copied code.
  28. Click on save.
  29. Let’s move on to implementing our following code, the Add to Cart code. Go back to the article and copy the Add to Cart code.
  30. Go to your Shopify dashboard.
  31. Click on Online Store from the left side menu. If you can’t find it, click on the Sales channel, and you’ll find the Online Store.
  32. Now click on the three dots menu beside your current theme section, and from the drop-down, click on Edit code.
  33. Search for buy-buttons.liquid, you should find it in the Snippets drop-down from the left-side menu.
  34. In buy-buttons.liquid, scroll down until you find the “ProductSubmitButton” code. In it, paste the copied code right below “name=add.”
  35. Click on save.
  36. Let’s move on to implementing our following code, the begin checkout code. Go back to the article and copy the begin checkout code.
  37. Again, open Theme,  Edit Code, and search for cart-notification.liquid. You should find it in the Snippets drop-down from the left-side menu.
  38. Find the checkout button, and paste the copied code after the “name=checkout.” 
  39. Click on save.
  40. Next, let’s implement our following code, the view cart code. Go back to the article and copy the view cart code.
  41. Again, open Theme,  Edit Code, and search for main-cart-footer.liquid. You should find it in the Sections drop-down menu on the left side.
  42. In the main-cart-footer.liquid, paste the copied code above the “{%- style -%}
  43. Click on save.
  44. In the same main-cart-footer.liquid, we have to paste the begin checkout code again as this is the second checkout button on our website. 
  45. Search for the checkout button in the code, and paste the begin checkout code after the “name=checkout
  46. Click on save.
  47. Let’s move on to implementing our last code, which is the purchase code. Go back to the article and copy the purchase code.
  48. Back to the Shopify dashboard, click on Settings from the button on the left side.
  49. In the settings menu, click Checkout and scroll until you find the Order status page. Underneath this, paste the purchase code in the Additional script.
  50. To test all tags, visit tagassistant.google.com and type your website. Now, check all tags and verify their firing statuses. Also, confirm whether the data is being sent to GA4 or not.

Video on how to set up Google Analytics 4 Shopify using Google Tag?

Important:

  • Keep in mind that not every Shopify Theme is the same. Use this cheat sheet if you have trouble with Shopify’s dynamic code.
  • This setup can be done on Shopify from the basics to the advanced level. If you are using Shopify Plus, you need some codes for the checkout.liquid.
  • I recommend you use the Google Tag Manager setup to have more control and be prepared for future server-side configurations.
  • Remember this is trial and error if your Shopify Theme is different.

Conclusion.

You have three ways to set up Google Analytics 4 on Shopify. Use these setups to help you understand what is working and what isn’t working on your website.

Also, you want your setup to be as correct as possible. However, remember that tracking prevention and privacy policies limit the possibility of tracking users. So, use GA4 to help you understand trends and patterns, and once you can see these trends and patterns, improve your marketing strategy to help your business grow.

Josipher & the Team

Get New Insights and Updates in CXO and MM.

Learn more

The GTM Template

You can get the GTM-Template-GA-4-Setup-Shopify here for 50 EUR to help you set up this faster.

You will get lifetime access to any updates or changes to the Template.

Get Your GTM Template