
February 1, 2022
The Magic of Google Tag Manager and Cookies
Updated: February 1st, 2022. Cookies are a super important part of the web. Imagine the world without them: you wouldn’t be able to use your Facebook or Twitter. They help retain data throughout a user’s visit on a webpage, so naturally, they’re an important component of web analytics, as well.
By default, Google Analytics and other analytics tools use cookies in order to track users’ behavior on your website. Unfortunately, I still see many marketers (working with GTM) suffering over not being able to fire Tags for returning visitors, or after 4 page views, etc.
But this shouldn’t be a problem since you can use Google Tag Manager to set and retrieve data from cookies in a fairly easy way. In this blog post, I’ll show you how to easily utilize cookies with Google Tag Manager and take your web tracking to the next level.
I remember when I was just starting to learn GTM. It was a giant leap for me when I realized I could set and read cookies without a developer’s help. It added much more flexibility and freedom to my tag management.
What if I need to fire a specific Pop-up if a visitor originally landed on my website from Adwords AND has already viewed 5 pages? Not a problem!
P.S. some screenshots in this blog post are using the older version of the GTM Preview mode but that should not affect your experience much.
Before we continue: this topic is also thoroughly explained in the Intermediate GTM Course
If you prefer video content over blog posts, then you should definitely consider enrolling in my Intermediate Google Tag Manager Course. In it, I will uncover many GTM features/tips/tricks that are often missed by intermediate users. Also, you will get a proper introduction to some technical topics that will help you go to the next level with GTM.

Why should you even bother with cookies? Few Examples
By setting and reading cookies with Google Tag Manager you can start creating much-sophisticated triggers, such as:
- A visitor has viewed 5 pages. Let’s show him a popup with a special offer!
- A visitor is actually a user in your SaaS (Software as a service) but is currently browsing without logging in. Nevertheless, he/she still has a cookie with value “registeredUser=true” which can be used as a condition for your trigger.
- A visitor has landed on your website via an affiliate link. With each page view, you can preserve affiliate ID in visitor’s cookie. Here’s the full guide on how to do that.
- Do you have a pricing page with price calculator? Let’s attach the calculator’s results (price) to that particular visitor. This way you’ll see how visitors with different price ranges are behaving on your site.
Pretty neat, huh?
So What’s the Plan?
- First, someone has to set the cookie. That might be either you (with help of Google Tag Manager) or a developer.
- Then, you need to create a 1st party cookie variable in GTM. It will look for a cookie with a particular name and make its value available in the data layer. You will also be able to see it in Google Tag Manager’s Preview and Debug mode.
- Create a trigger where condition involves the aforementioned 1st party cookie variable.
- Fire a tag based on a trigger from bullet point No. 3.
- Profit.

Set cookies with Google Tag Manager
In order to set a cookie, you’ll need to create a custom HTML tag. It contains Javascript code which defines cookie’s name, expiration time, etc.
<script> (function(){ var cookieName = "visitorFromAdwords"; // Name of your cookie var cookieValue = "true"; // Value of your cookie var expirationTime = 2592000; // One month in seconds expirationTime = expirationTime * 1000; // Converts expirationtime to milliseconds var date = new Date(); var dateTimeNow = date.getTime(); date.setTime(dateTimeNow + expirationTime); // Sets expiration time (Time now + one month) var date = date.toUTCString(); // Converts milliseconds to UTC time string document.cookie = cookieName+"="+cookieValue+"; SameSite=None; Secure; expires="+date+"; path=/; domain=." + location.hostname.replace(/^www\./i, ""); // Sets cookie for all subdomains })(); </script>
In the script above, there are three variables that you should edit:
- cookieName – you should give it a meaningful title, e.g. visitorFromAdwords, affiliateID, pageviewCount, etc.
- cookieValue – In case of visitorFromAdwords possible values can be true or false. affiliateID cookie’s value can be 2385437, and pageviewCount cookie’s – 5.
- expirationTime defines when the cookie expires. 2592000 is 30 days converted to seconds (30 days * 24 hours * 60 minutes * 60 seconds * 1000 milliseconds). If you want the cookie to expire after the session ends (when the browser window is closed), then remove expires=”+date+”; from the end of the script. Keep in mind, that Google Chrome still runs in the background when you close the browser window, thus the cookie will “live” longer.
Now, you need to decide when you want to set that cookie. Should this “set cookie” script fire when URL contains ?gclid= (meaning that a visitor landed via Adwords campaign)?
Say, we want to set cookies for those visitors, who have found our website via Google Adwords. In that case, we need to create a trigger with the following settings.
When a person clicks any Google ad, a destination URL contains ?gclid=XXXXXX. That’s the reason behind this trigger’s condition.
Test The Cookie
After you created custom HTML tag with the cookie-setting script and its trigger, next thing you should do is test the implementation with Preview and Debug mode. Make sure that the tag fires ONLY when URL contains ?gclid=. If you’re new to Preview and Debug mode, read this comprehensive guide.
Now, let’s check whether a cookie is set correctly. There are two main ways to check cookies – the browser’s built-in feature (developer tools) or a plugin.
Personally, I am using Chrome plugin called EditThisCookie (also available for Opera users). This really simple and intuitive extension enables me to quickly check which cookies are currently in use and what data do they contain.
If you haven’t already installed, download it here. If you’re using a different browser, you’ll need to find something on your own.
Anyway, let’s get back to EditThisCookie. Once you have installed this extension, a cookie icon will appear next to the Menu icon (in Chrome).
Go to the website you’re currently working on, click EditThisCookie icon and you’ll see an expanded list of all cookies that are currently in use on that website. Look for a cookie named visitorFromAdwords. This little piece of data will help us do the magic in further chapters of this blog post.
Read The Cookie
Now, we need to “teach” Google Tag Manager read the cookie and make it available as a variable. Go to your GTM account, open list of Variables, and create a new user-defined variable with the following settings:
This variable searches for cookies with title visitorFromAdwords. If it spots one, GTM will read its value and make it available in the Variables tab of Preview and Debug console.
This enables you to use visitorFromAdwords variable in any GTM tag or trigger, like in the example below:
Example – Fire a Tag on 3rd Page View
This is one of the most popular use cases of cookies with Google Tag Manager. For your convenience, I have prepared a GTM Recipe with a ready-made script that counts the number of page views and fires a trigger after 3. But if you’re eager to understand the details, continue reading.
Let’s Count Page Views
First of all, you’ll need to create a custom HTML tag that counts page views. Every time a page refreshes, this script searches for cookie pageviewCount and increments its value by 1.
<script>function setCookie(name, value, expires) { var cookie = name + "=" + value + "; path=/; domain=." + location.hostname.replace(/^www\./i, ""); if (typeof expires !== "undefined") { var now = new Date(); now.setTime(now.getTime() + expires * 24 * 60 * 60 * 1000); cookie += "; expires=" + now.toUTCString(); } document.cookie = cookie; } function getCookie(name) { var cookies = document.cookie.split(";"), toReturn; for (var i = 0; i < cookies.length; i++) { var cookie = cookies[i].trim(); if (cookie.indexOf(name + "=") === 0) { toReturn = cookie.substring((name + "=").length, cookie.length); } } return toReturn; } (function() { var pageviewCount = getCookie("pageviewCount"); if (typeof pageviewCount === "undefined") { pageviewCount = 1; } else { pageviewCount++; } setCookie("pageviewCount", pageviewCount, 30); })(); </script>
The cookie (set by this Javascript) expires after 30 days. You can easily change its duration by editing setCookie(“pageviewCount”, pageviewCount, 30).
Set this custom HTML to fire on all pages. Refresh Preview and Debug mode, open EditThisCookie plugin and check whether the cookie was successfully saved. Now, refresh the page. Cookie’s value should increase to 2.
If you want this cookie to be valid only for that visitor session, here’s a modified script (I’ve removed all parts which are related to the expiration date). Keep in mind, that Chrome handles cookies a bit differently (compared to other browsers). Even if you close the tab or window, Chrome still might keep running in the background, therefore session cookies might be still valid.
<script>function setCookie(name, value) { var cookie = name + "=" + value + "; path=/; domain=." + location.hostname.replace(/^www\./i, ""); document.cookie = cookie; } function getCookie(name) { var cookies = document.cookie.split(";"), toReturn; for (var i = 0; i < cookies.length; i++) { var cookie = cookies[i].trim(); if (cookie.indexOf(name + "=") === 0) { toReturn = cookie.substring((name + "=").length, cookie.length); } } return toReturn; } (function() { var pageviewCount = getCookie("pageviewCount"); if (typeof pageviewCount === "undefined") { pageviewCount = 1; } else { pageviewCount++; } setCookie("pageviewCount", pageviewCount); })(); </script>
Cookie variable and trigger in Google Tag Manager
Since we have created pageviewCount cookie, now it’s time to “teach” Google Tag Manager read the cookie and make it available as a variable. Go to your GTM account and open a list of Variables. Create a new user-defined variable with the following settings:
Next, go to Triggers and create a new Page view trigger with the following settings:
This trigger will fire when the cookie’s value is greater or equal to 3.
That’s it! You can now assign this trigger to any tag you want, whether it is a pop-up or Google Analytics event tag, or whatever. It’s up to your imagination.

Delete a Cookie
If you want to delete a particular 1st-party cookie, you need to set its expiration time to the past date, e.g. 1970 January 1st. Such cookies cannot exist, therefore, they immediately expire.
Here’s a script that you should use:
<script> (function() { var name = 'yourCookieName'; // REPLACE yourCookieName WITH THE NAME OF THE COOKIE YOU WANT TO DELETE var path = ''; // If needed, replace this var domain = ''; // If needed, replace this document.cookie = name + "=" + ((path) ? "; path=" + path: "") + ((domain)? "; domain=" + domain: "") + ";expires=Thu, 01 Jan 1970 00:00:01 GMT"; })(); </script>
In the 3rd line of the code, change yourCookieName with the name of a cookie you wish to delete. This code should also be implemented via GTM Custom HTML tag and fired whenever you need to delete a cookie (e.g. after a conversion, opt-out or something else).
Also, if your cookie has a specified domain and path, insert the values in the ‘path’ and ‘domain’ variables (in the JavaScript code). But you can start by keeping those field (in 4th and 5th lines) empty and see if it works.
Few More Ideas
If you still don’t know how to leverage cookies in your marketing stack, here’s food for thought. I hope these examples will help you break the ice:
- If you run an affiliate program, you already know that visitors come to your site via affiliate links (which contain unique affiliate ID). You can fetch that data from URL, set it as a cookie and send to Google Analytics as Custom Dimensions. This way you’ll see how well/terrible affiliate traffic is converting. Also, you can identify which affiliate partner is driving the most engaged traffic.
- If a person made a purchase on your site, save this fact as a cookie. Then, create a pageview trigger that blocks pop-ups (irrelevant to recent buyers).
- If you run a SaaS business, ask developers to set various data about the user to cookies. Even if the user is logged out, you can still identify him/her visiting your website/blog/etc. and send that data to Google Analytics as custom dimensions. But be aware of PII limitations.
Not all 1st party cookies can be read with Google Tag Manager
In fact, this applies not only to GTM but to client-side JavaScript in general. If you’re already familiar with cookies, you know that all the cookies (set on that page) can be seen by going to your browser’s developer tools. I’m using Chrome, therefore, the full path to that part is Chrome’s Menu > More Tools > Developer Tools > Application > Cookies.
Then choose your domain. You should see something like this:
Those are the 1st party cookies you could potentially use in Google Tag Manager. Various scripts and other functionality on your site set those cookies to your visitors’ browsers. However, not all of them can be accessed by JavaScript in your browser (including GTM).
If a cookie has a checkbox in the HttpOnly column, GTM will not be able to access its value. This means that a 1st party cookie variable will return undefined.
Working with cookies and Google Tag Manager: Final Words
So there you have it. Turns out it’s pretty easy to manage cookies with Google Tag Manager. First, you need to fire a custom HTML tag that sets the cookie with a particular value. Then, you need to create a 1st party cookie variable within GTM.
This variable’s value can be transferred to other tools (such as Google Analytics) or used as a firing condition within a trigger.
If you’re looking for ways how to fire a particular tag after 3 page views, or for those visitors, who have visited a particular page, then cookies should be your weapon of choice. Another solution is browser storage (localStorage and sessionStorage), but that’s a topic for another time.
Do you know more tricks on how to use cookies with Google Tag Manager? Let me know in the comments.
By the way, I’ve noticed some people asking the question “does Google Tag Manager use cookies by default?”. They are worried about various privacy regulations. To answer that, I’ve published a blog post.

70 COMMENTS
Hello,
this is a fantastic way to measure the content engagement and create some smart metrics that can really impact the business bottom line.
Much thanks for this solution. If I could ask 2 question.
1. The cookie is valid till the end of the session (30min) or if the user returns to the site after one week it will continue to count the pageviews where it ends for current cookie?
2. Do you have an idea how to find out which page was last pageview?
Thanks a lot for great blog and really appreciate your work
have a great day
Just to clarify question 2.
What i would like to know what was the total count of pages for "user"/client id to make some deeper analysis to find out what value certain page has.
is there a chance to fire a special tag in GTM when the user sees last page and i will be able to grab the count of how much pages there were before they reached the current page?
hope it is a bit understandable, anyway, pardon me the little messy explanation.
Thanks a lot
Hey,
1. One cookie can be have only one expiration date: either session, either 1 week. If your cookie expires after session AND then user returns after 1 week, page view counter will start counting from start (1).
2. Sorry, I am still not sure whether I understood the 2nd question. If you wish to see how many page views or sessions do your visitors make, you can go to Audience > Behavior > Frequency and Recency. Did that answer your question?
This is glorious. Great work Julius!
Hi, how do I set the cookie to expire at the end of the session in the "Let's count pageviews" code.
If I remove 30 from this part of the code I get an error: setCookie("pageviewCount", pageviewCount, 30);
Hi Julius, can you answer my question please? Thx!
Hey, sorry, somehow I missed your comment. In order to create a cookie which is valid only for that session, you do not need to edit "Let's count pageviews" script. Instead, use the very first script (in "Set cookies with Google Tag Manager" section) and edit two things:
1. Remove the line no. 5 (var expirationTime = 2592000; // One month in seconds)
2. Edit line no. 12 by removing expires="+expirationTime+"; As a final result, the line no. 12 should look like this:
document.cookie = cookieName+"="+cookieValue+"; path=/; domain=." + location.hostname.replace(/^www\./i, "");
What I did here was to remove everything that has something to do with Expiration. If expiration setting is not defined, the cookie will be active only during that session. But keep in mind how Chrome handles sessions. Even if you close the browser window, Chrome might keep running in the background, therefore that session cookie might still be available.
Cheers
Hi Julius,
Thx for your reply. I think you misunderstood me. I have to use the "Let's count pageviews" script, cause that's what I want to do (count page views and store them in a cookie). As you say in your explanation:
"this script searches for cookie pageviewCount and increments its value by 1."
The cookie pageviewCount is set by creating a user defined variable in GTM. Like you explained here:
"Go to your GTM account and open list of Variables. Create new user-defined variable with the following settings:"
So if I want the cookie pageviewCount to only live during the session, I'll have to update the "Let's count pageviews" script. This is what led me to my question.
If I remove 30 from this part of the code in the "Let's count pageviews" code, I get an error: setCookie(“pageviewCount”, pageviewCount, 30);"
Yes, apparently, I indeed misunderstood you. I've updated the blog post by adding an additional, modified, script which creates a cookie valid only for that session. You can find it below the paragraph you've quoted in your last comment. Keep in mind that issue with Chrome is still possible.
Cheers
Great! Thx for this!
Hello! Awesome script. Is there a way to modify the pageviewCount script so that it counts number of sessions as opposed to pageviews? Rather than counting how many times a page is viewed, I was hoping to use the cookie to determine how often a customer comes back to the site to check on prices or products. Thanks!
Hey, not sure. This is a whole another level of JavaScript development. And I'm not very efficient with it. On one hand, this idea sounds a bit hacky and might cause a lot of inaccurate data but maybe I'm wrong.
Hi Julius,
thank you so much for this article! I would like to ask a question:
I am tracking form submissions on my website right now and here is what a typical journey of a user looks like:
1) Reach product landing page (urls are tagged with UTM, e.g. ?variable=facebook)
2) Clicks on product interest submission form and is redirected to a third party site where they can select their choice of product
3) is redirected back to my site where they can proceed to submit the form which grabs the product of their choice from the third party site
Can i use this method as stated in the article to preserve the cookie from step 2 to step 3 so i am able to attribute to form submission back to facebook?
Thank you!
Yes, you can.
Set the cookie in step 1 (I'd set its duration to a couple of hours, but you know your business/website better than me). When the user is redirected back to your site in step 3 and submits the form, fire all conversion tags you need and then fire one more Custom HTML tag which deletes the cookie.
Here's a solution how to delete a particular cookie by name (set its date to the past) https://stackoverflow.com/questions/10593013/delete-cookie-by-name (see the most upvoted answer). Take that code snippet, change cookie's name and paste the code to Custom HTML tag.
You are the best. This is the most helpful article. Thank you very much. As for how to use a cookie - I have a situation where our customer help agents open sessions logged in as customers and place orders for them. In every way during the session, this looks as if the customer is placing the order, but I need to create reports specifying when it's an agent and when it's a customer. Setting a cookie just when the agent starts the session is the trick. Thank you again!
Happy to help!
Hi Julius,
Thanks for this article. We have three different enviroments in one site. Each enviroment has a subdomein adres like: shop.site.com, community.site.com and www.site.com. The cookie can be first set by a visit in one of the enviroments. But in another enviroment I wish to use it.
So for example a visitor lands in the community.site.com. I start the pageview cookie, count the pageviews. The vistor jumps to shop.site.com and I add these pageviews. Leaves the site. Comes back a few days later to www.site.com and I wish to continue counting.
How do I set and read a cookie over these subdomains. I suppose I like to have a *.site.com cookie. But how? Do you have a suggestion?
Hi, the script that I've shared in this blog post takes the hostname of the current page and adds a "dot" at the beginning (and removes www). So if a visitor is on community.site.com, the cookie will be added to ".community.site.com", as a result, the cookie will not be reached by the www.site.com.
Here's a solution:
Change the 12th line from
document.cookie = cookieName+"="+cookieValue+"; expires="+expirationTime+"; path=/; domain=." + location.hostname.replace(/^www\./i, "");
to
document.cookie = cookieName+"="+cookieValue+"; expires="+expirationTime+"; path=/; domain=.site.com"
Just change "site.com" to the actual domain (without subdomains).
Thanks Julius,
Now I understand the code better.
Hi there
Hoping you can advise/help. I've been reading elsewhere that in line with GDPR, you should on first visit to a site give visitors the option to activate and deactivate specific types/groups of cookies. This includes the usual Analytics cookies as also any linked to Tag Manager. The general advice I've read is that these should be turned off by default and giving a toggle switch opportunity to turn them on. Assuming this is correct and visitors don't bother to activate that group of cookies, will this mean that any use of tracking via Tag Manager for things like form submissions, Adwords and general site stats is rendered useless?
Hey, if cookies do not contain personal information about the visitor, then you have no problem (or if those cookies are not sent to other systems).
To be honest, I'm still not sure what's going to happen next. Looks like the privacy law was prepared without looking at what's happening in the market. Also, the ePrivacy (new cookie law) is still not finished (it's expected to be prepared at the end of 2018), maybe it will shed some light.
Some parts or GDPR are so hardcore, that even EU regulators themselves are not prepared, here's the source: https://www.reuters.com/article/us-europe-privacy-analysis/european-regulators-were-not-ready-for-new-privacy-law-idUSKBN1I915X
My position here would be to:
- implement a semi-compliant cookie consent which lets visitors act before being tracked (with the possibility to disable tracking) and all (or the majority) of tracking groups would be pre-checked.
- Enable anonymized IP in GA, probably disable Display Advertising features.
- Fire tracking pixels when the consent is given but it would be very easy to do so.
- Wait and see.
Once again, I've read GDPR, I am aware of their suggestions, but seeing what's happening around (with other companies), I'm choosing to comply with the majority of requirements but not all.
And then I'll see what happens on the market. Since even the EU itself is not ready yet, I don't think that (at least for now) there will be fines or big lawsuits for small/medium businesses. Large corporations maybe could be worried more.
But that's just my position which can be easily changed/manipulated. So don't ever take this as a legal advice.
By the way, I've seen some folks developing a content gate, which works as follows:
- First step - "Are you from EU?"
- If a visitor chooses "No", all tracking works normally
- If a visitor chooses "Yes", then another gate appears which offers to Accept all cookies with one click and a link to cookie settings.
That way at least some portion of data will remain intact.
Really helpful article,
Could you provide a little more detail on implementing the 'Affiliate ID' use case? I have a URL that passes a unique value (e.g. www.domain.com/?src=XXXXXX), I was able configure a GTM variable to pass the value to GA as a custom dimension, but do not understand how to edit the cookie script to set those unique values on subsequent pages.
Hey, here's the guide that can help you https://www.analyticsmania.com/post/track-affiliate-sales-with-google-tag-manager-and-google-analytics/
Hi Lulius,
On My site We have integrated Google tag manager code snippets which are given
https://developers.google.com/tag-manager/quickstart
When it is executing its creating some cookies with name _utma, _utmb, _utmc etc.. Cookies are created without http and secure attribute, this is security concern and raised by our scanner team.
Could you please suggest how to make these cookies with http and secure attribute?
Please suggest.
These cookies have nothing to do with GTM. They belong to Google Analytics. In fact, they belong to Classic Google Analytics which is an outdated technology. You should migrate to Universal Analytics, which is the new version. And by saying "Migrate" I mean that you need to refactor the entire GA tracking implementation and start using Universal Analytics tags.
Hi Julius,
Is there any way to create a tag to fire after completing 60 sec session duration (not in a single page - consider the entire session)
This method affects the average session duration, not the avg. time spent on page. Sounds strange but that's how Google Analytics works. Read more about how these two metrics are calculated
The average time on page is just a difference between one page load and another. Events do not affect it.
How the final code for setting up a session cookie should look like?
The code example in this blog post looks like the final code.
Thanks for the quick reference. Came in very handy this morning wrapping up a project :)
Thanks for sharing this - super useful!
Hi Julius, this is the best article on cookies for GTM. I have a question, how is it possible to setup a Variable with First Party Cookie to teach GA to read a cookie from a CRM system (Microsoft Dynamics)?
I know that it's possible to send CRM data to GA, bur I need to find the CRM cookie name, any clue on how to achieve this would be amazing!
If you're working on Chrome > More Tooles > Developer Tools > Application > Cookies, Choose the domain of your website. You will then see all the first-party cookies that are available to be read (if they don't have the checkbox HTTP or Secure).
How to find out which cookie do you need? I'd google that and search forums. There are no strict rules on how to name cookies, therefore, I cannot tell you the final answer.
Hi Julius,
Thank you for the guide - it is incredibly detailed and clear.
But a question - is there anything like a "Cookie Listener" for when a cookie gets created or updated?
I understand, that the question is somewhat strange - but I am in a situation where I may need something like this.
You could try something like this
https://stackoverflow.com/questions/14344319/can-i-be-notified-of-cookie-changes-in-client-side-javascript
I haven't done it myself, though
Thanks for this Julius!
How can I make sure these cookies fire domain1.com and also on domain2.com?
Cookies set on domain1.com cannot be accessed on domain2.com.
How to check if a cookie has been set? Use editThisCookie extension or browser's dev tools (I have mentioned them in this guide)
Hi Julius,
You noted above that "I still see many marketers (working with GTM) suffering over not being able to fire Tags for returning visitors"
Just wondering if you know of any recipes to place a 1st party cookie that counts number of session / visits ?
Apologies if this is a dumb question, I may be using the wrong search terms in google
thanks
This is not dumb. This is very complex. There are many things that affect sessions in GA, therefore, trying to replicate that logic with Javascript in GTM will cause a lot of inaccuracies.
Hi Julius
I have set a number of 1st party cookies via GTM that last for 30 days, 1 year and 2 years but it appears they have all defaulted to a duration of 1 year. They were previously working as intended as I test a lot before making live.
I've tripled check my setup (i.e. the correct seconds have been entered into the cHTML tag) and these all appear fine.
Have you come across this before?
Thanks
Hi Julius
My 1st party cookies appear to be getting reset when I close my browser (both in EditThisCookie and F12 - developer tools). I've checked my chrome security settings and nothing in the cookie setting should be causing this. Have you ever come across this problem?
I've pasted by cHTML code below (note it has been edited to allow for cookies to be palced across subdomains). Any help would be much appreciated
<script>
var cookieName = "pGT"; // Name of your cookie
var cookieValue = "true"; // Value of your cookie
var expirationTime = 63072000; // two years in seconds
expirationTime = expirationTime * 1000; // Converts expirationtime to milliseconds
var date = new Date();
var dateTimeNow = date.getTime();
date.setTime(dateTimeNow + expirationTime); // Sets expiration time (Time now + two years)
var date = date.toUTCString(); // Converts milliseconds to UTC time string
document.cookie = cookieName+"="+cookieValue+"; expires="+expirationTime+"; path=/; domain=.site.com" // Sets cookie for all subdomains
</script>
Hi Julius
Apologies to keep hounding you, but wondering if you can assist with my question above? I've tried everything and cannot find a solution.
If it helps, when debugging in chrome developer tools it appears as if all first party cookies I've placed using this article are only set for the session, not for the time period I specified in the cHTML tag (i.e. 1 year).
You have edited the code too much. You just need to change the first 3 lines of code (var cookieName, cookieValue, expirationTime). Just as I instructed in the video. Don't change anything else in the code.
thanks for your reply, Julius. Much appreciated.
I made additional changes to the code so I could place first party cookies across domains. These changes were based on your comment below to another reader's question about cookies across subdomains. I've troubleshooted this again and when I only edit the first 3 lines, cookie can't be placed across subdomains. When i make the change below the cookie is available across sub domains but the cookie only lasts for the session (not the time period specified in the cHTML).
"Here's a solution:
Change the 12th line from
document.cookie = cookieName+"="+cookieValue+"; expires="+expirationTime+"; path=/; domain=." + location.hostname.replace(/^www\./i, "");
to
document.cookie = cookieName+"="+cookieValue+"; expires="+expirationTime+"; path=/; domain=.site.com"
Just change "site.com" to the actual domain (without subdomains)."
That comment's code is outdated. Take the original code from my blog post. Then change only a part of the 12th line.
domain=.yourdomain.com"
Leave everything else in that line as it is.
Hi Julius
Thank you so so much for your response. Really appreciate it! This has solved most of my problems which is great. However, I am still not able to track across subdomains.
For example, when someone makes a purchase on parking.perthairport.com.au I need the cookie to be available on perthairport.com.au. I follwed your instrcution to: "change only a part of the 12th line.domain=.yourdomain.com" but the solution doesn't appear to be working
My cHTML is below for your reference
<script>
var cookieName = "parkingTransaction30"; // Name of your cookie
var cookieValue = "true"; // Value of your cookie
var expirationTime = 2592000; // One month in seconds
expirationTime = expirationTime * 1000; // Converts expirationtime to milliseconds
var date = new Date();
var dateTimeNow = date.getTime();
date.setTime(dateTimeNow + expirationTime); // Sets expiration time (Time now + one month)
var date = date.toUTCString(); // Converts milliseconds to UTC time string
document.cookie = cookieName+"="+cookieValue+"; SameSite=None; Secure; expires="+date+"; path=/; domain=.perthairport.com.au" + location.hostname.replace(/^www\./i, ""); // Sets cookie for all subdomains
</script>
Hi Julius
Thank you so so much for your response. Really appreciate it! This has solved most of my problems which is great. However, I am still not able to track across subdomains.
For example, when someone makes a purchase on parking.perthairport.com.au I need the cookie to be available on perthairport.com.au. I followed your instruction to: "change only a part of the 12th line.domain=.yourdomain.com" but the solution doesn't appear to be working
My cHTML is below for your reference
<script>
var cookieName = "parkingTransaction30"; // Name of your cookie
var cookieValue = "true"; // Value of your cookie
var expirationTime = 2592000; // One month in seconds
expirationTime = expirationTime * 1000; // Converts expirationtime to milliseconds
var date = new Date();
var dateTimeNow = date.getTime();
date.setTime(dateTimeNow + expirationTime); // Sets expiration time (Time now + one month)
var date = date.toUTCString(); // Converts milliseconds to UTC time string
document.cookie = cookieName+"="+cookieValue+"; SameSite=None; Secure; expires="+date+"; path=/; domain=.perthairport.com.au" + location.hostname.replace(/^www\./i, ""); // Sets cookie for all subdomains
</script>
Hi Julius,
I have followed the steps for this blog multiple times successfully so thank for all your help!
However I am trying to set it up another time using the exact same code and method but it isn't working. The tag is firing successfully but no cookie is being created.
My code is as follows:
<script>
var cookieName = "installIntent"; // Name of your cookie
var cookieValue = {{Session ID}}; // Value of your cookie
var expirationTime = 1800; // One month in seconds
expirationTime = expirationTime * 1000; // Converts expirationtime to milliseconds
var date = new Date();
var dateTimeNow = date.getTime();
date.setTime(dateTimeNow + expirationTime); // Sets expiration time (Time now + one month)
var date = date.toUTCString(); // Converts milliseconds to UTC time string
document.cookie = cookieName+"="+cookieValue+"; SameSite=None; Secure; expires="+date+"; path=/; domain=." + location.hostname.replace(/^www\./i, ""); // Sets cookie for all subdomains
</script>
HI Julius,
I've followed these steps and I see the cookie is active and value=true in the cookie extension, but in GTM variables it's being passed as undefined. Do you know why this would be happening?
Either your cookie variable contains an incorrect name or you are trying to access httponly cookie, which cannot be accessed by Javascript (including GTM).
Hi Julius,
Thanks for the article and the information.
I have a question, I have two identical tags except for one feature (support doc.write) that I want them to fire based on the cookie value (A or B) 50%/50% so I can measure the efficiency. Do you know of a way to do this? Many thanks!
Hi Julius,
Nice article. Wanted to know that when we storing the value = visitor from Adwords = True in a cookie, and then firing the Trigger-based on cookie value and eventually firing any tag based on it,
WHY we cannot do it directly without the cookie method, like firing an event tag when trigger condition = Page URL contains ?gclid . This will evetually fire an event tag when a visitor lands on the website from Ads.
Why we take the cookie route? What's the advantage more than just sending data to GA?
Also you mentioned we can use pop up to show based on cookie values, but GTM ideally is JUST used to send data to tools, how can we use it to show pop up?
Thanks,
What if I go to another page before the conversion? your gclid parameter will no longer be in the URL
Hi Julius, thanks for this thorough article! I've been trying to use this method to track internal visits from our Intranet and then exclude them in our GA reports. This might seem strange, but since all our employees work from home due to the coronavirus, our 'Exclude IP' filters in GA do not work anymore. So I've put a cookie on our Intranet which says 'Internal traffic = true', which is working fine. But I can't figure out how to pass the value of the Intranet cookie (which is a subdomain) to our main domain. Both domains have separate GTM containers. I've enabled cross-domain tracking in both containers and altered the custom html code as you stated in a previous comment. Do I have to put the GTM container from the main domain on the Intranet subdomain as well? Thanks!
Just send the value of the cookie as a custom dimension. Then create a GA filter that excludes the traffic with that particular custom dimension.
Hi Julius, thanks for your help! I think I still do something wrong. I made a custom dimension, set it to user scope with a value of 'true' (the same value I put in the cookie). Then I made a filter, saying Exclude - (name of custom dimension) - filtern pattern 'true'. But my amount of visitors is still the same. Did I pick the wrong scope in the custom dimension? Thanks again!
Hi Julius,
If you've answered this question already I apologize.
Once the cookie is created, I'd like to pass the cookie value across domains if the user takes that journey or if they return to 1 of the 3 domains I'm tracking. I have cross domain tracking in place.
Is this possible to do?
Hi Julius,
Thanks for sharing this information. As you know that cross site tracking has set to be disabled in IOS 14 limiting us to track events on safari and other privacy enabled browser. If I implement above method, will I a be able to track user behaviour on the website?
Hello Julius, I found this extremely helpful and great thanks for sharing it!
May I ask a questions about cross device tracking?
-> Can the value stored in the 1st party cookie be grabbed by GTM when the user use another device (with same browser)?
-> e.g. Day 1 - user desktop chrome - a value stored in 1st party cookie -> Day 2 - user mobile chrome accessing the same website -> could the value stored in the cookie be accessed by GTM when the user visit from mobile?
Thanks!
Hi, cookies are not shared between devices
Hi testing comment working or not. Because cannot see my comment posted here
Seems to be my post is too long. Let me try to shorten the post.
User visit from Facebook ad to my landing page with a URL that contain some UTM parameter:
mylandingpage.com/signup?utm_source=FB&utm_medium=TrafficAd&utm_campaign=Prep4Exam
User clicks on a CTA from landing page which direct the user to an external payment domain which I don't have any control. When payment completes, the user re direct to mylandingpage.com/thank-you. But without any UTMs. Here I face real problem. I sent thank you page view as a conversion events to GAU that created using GTM. GAU shows conversion event in reports but without the medium/source/campaign. I mean the payment gateway domain name is showing under source and 'referral' under medium which I have no use.
Is there any solution?
Can we save the UTMs in cookies when a user land on landing page, and add those stored UTMs in URL when the same user return to mylandingpage.com with in an hour or something like that?
Hi Julius,
Thanks for all your helpful posts on GTM and GA4. I would be lost without this blog.
In this post you mention the possibility of showing a popup using this method. I know I would really appreciate if you had an example of this. Just to see how you might approach it for a Wordpress site perhaps (using an installed popup plugin, or another method?). I realize this is off-scope a bit, but i can't figure this out, and need a hint.
Hi, read this https://www.analyticsmania.com/post/annoy-email-subscribers-less-with-google-tag-manager/
Hey Julius,
I ran this cookie and it does not fire (despite race conditions being met) on my subbdomains...only my domain. I can see the cookie in applications purely if I run the conditions for the tag to be pageview on the main domain, and if I set it to launch/run on a subdomain - no luck.
You must set a cookie on .yourdomain.com (with a dot in front of it)
Hi Jules, I used the cript that counts the number of page views and fires a trigger after 3. The cookie works in EditThisCookie, however the tag I added to the trigger is not fired. In Tag Assistent I see "NaN" as the value of the cookie. Do you know how I can solve this?
Hi Julius,
Is this a good approach (starting point) to create a cookie to use it the to exclude our own visits to our site?
Walter
If IP is constantly changing then cookie is a viable option
Hi Julius, thank you for the post, the tag is being fired properly. I have this issue: i set the tag to be fired at the 5th page viewed, the problem is that the tag fires for every other page viewed after the 5th page. I would like to generate an unique event every time the user views more than 5 pages, but if for example the user visits 8 pages the tag will fire 4 times (first one after the 5th page + other 3 times at the 6th, 7th and 8th page viewed). Is there a way to have an unique event firing the tag only once per user session? Thank you, Paolo