• Courses
    • Courses
    • Course bundles
  • Blog
  • Resources
    • Youtube channel
    • E-books and Guides
    • GTM Recipes
    • View All Resources
    • GTM Community
    • GA4 community
  • Services
  • About
    • About
    • Contact
  • Login
  • Courses
    • Courses
    • Course bundles
  • Blog
  • Resources
    • Youtube channel
    • E-books and Guides
    • GTM Recipes
    • View All Resources
    • GTM Community
    • GA4 community
  • Services
  • About
    • About
    • Contact
  • Login

April 3, 2025

The Magic of Cookies with Google Tag Manager

Updated: April 3rd, 2025

Cookies are a vital aspect of the average user’s internet experience (of course, there are some side effects, too). Still, the initial idea was novel – to have a more personalized experience across the web.

Cookies are handy for marketers, too. They retain information that helps better understand users’ browsing behavior, which can then be used to improve your marketing efforts.

By default, Google Analytics and other analytics tools use cookies to track a user’s behavior on your website. Unfortunately, I still see many marketers (working with GTM) suffering from being unable to fire Tags for returning visitors or after 4 page views, etc.

But this shouldn’t be a problem since you can easily use tag managers to set and retrieve data from cookies. In this blog post, I’ll show you how to efficiently utilize cookies with Google Tag Manager and take your web tracking to the next level.

I remember when I was starting to learn GTM. It felt like a real level-up 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 initially landed on my website from Google Ads AND has already viewed five pages? Not a problem!

 

Before we continue: this topic is also thoroughly explained in the Intermediate GTM Course

If you prefer video content over blog posts, consider enrolling in my Intermediate Google Tag Manager Course. In it, I will uncover many GTM features/tips/tricks that intermediate users often miss. Also, you will get a proper introduction to some technical topics that will help you go to the next level with GTM (including cookies).

Enroll in Intermediate Google Tag Manager course

 

Why should you even bother with cookies? Few Examples

By setting and reading cookies with Google Tag Manager, you can start creating more sophisticated triggers, such as:

  • A visitor has viewed five pages. Let’s show him a pop-up with a special offer!
  • Suppose a visitor on your SaaS (Software as a Service) website is actually a user but is currently browsing without logging in. Nevertheless, they still have a cookie with the value “registeredUser=true”. This condition is good to use for your trigger.
  • A visitor has landed on your website via an affiliate link. You can preserve the affiliate ID in the visitor’s cookie with each page view. Here’s the full guide on how to do that.
  • Do you have a pricing page with a price calculator? Let’s bind the calculator’s results (price) to that particular visitor with the help of a cookie. This way, you’ll see how visitors with different price ranges behave on your site.

Pretty neat, huh?

 

So What’s the Plan?

To create a cookie in Google Tag Manager and use it in tags/triggers, follow these steps:

  1. Create a cookie with a tag
  2. To access that cookie, create a 1st-party cookie variable
  3. Create a trigger where the condition contains a 1st party cookie variable.
  4. Fire a tag based on a trigger from a bullet point from step no. 3.

Let’s take a closer look at each step.

 

Set cookies with Google Tag Manager

The first thing you need to do is to create a custom HTML tag when setting up a cookie. It contains JavaScript code that defines the cookie’s name, expiration time, etc.

<script>
(function(){
    var cookieName = "visitorFromGoogleAds"; // Name of your cookie
    var cookieValue = "true"; // Value of your cookie
    var expirationTime = 2592000; // One month in seconds
    expirationTime = expirationTime * 1000; // Converts expiration time 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

    // Extract base domain
    var domainParts = location.hostname.split('.');
    var baseDomain = domainParts.slice(-2).join('.'); // Get the last two parts of the domain

    document.cookie = cookieName + "=" + cookieValue + "; SameSite=None; Secure; expires=" + date + "; path=/; domain=" + baseDomain; // 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., visitorFromGoogleAds, affiliateID, pageviewCount, etc.
  • cookieValue – In the case of visitorFromGoogleAds possible values can be true or false. For example, affiliateID cookieValue 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), remove expires=”+date+”; from the end of the script. Remember 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. For example, should this “set cookie” script fire when the URL contains ?gclid= (meaning that a visitor landed via a Google Ads campaign)?

Say we want to set cookies for those visitors who have found our website via Google Ads. In that case, we need to create a trigger with the following settings.

When a person clicks any Google ad, the destination URL contains ?gclid=XXXXXX. That’s the reason behind this trigger’s condition.

Subscribe and Get the Ebook - Server-side tagging

 

Test The Cookie

After creating a custom HTML tag with the cookie-setting script and its trigger, you should next test the implementation with Preview and Debug mode. Make sure that the tag fires ONLY when the URL contains ?gclid=. If you’re new to Preview and Debug mode, read this comprehensive guide.

Now, let’s check whether a cookie has been correctly set. There are two main ways to check cookies – the browser’s built-in feature (developer tools) or a plugin.

I use a Chrome plugin called EditThisCookie (also available for Opera users). This simple and intuitive extension lets me quickly check which cookies are currently used and what data they contain.

If you haven’t already installed it, download it here. You’ll need to find something on your own if you’re using a different browser.

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 working on, click the EditThisCookie icon, and you’ll see an expanded list of all currently used cookies. Look for a cookie named visitorFromGoogleAds. 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 the list of Variables, and create a new user-defined variable with the following settings:

This variable searches for cookies with the title visitorFromGoogleAds. If it spots one, GTM will read its value and make it available in the Variables tab of the Preview and Debug console.

Following the above steps enables you to use visitorFromGoogleAds variable in any GTM tag or trigger, like in the example below:

 

Example – Fire a Tag on 3rd Page View

Firing a specific tag after a certain number of pageviews 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.

DOWNLOAD THIS GTM RECIPE

 

Let’s Count Page Views

First, 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 the EditThisCookie plugin, and check whether the cookie was saved. The 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 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 still be 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 created a pageviewCount cookie, it’s time to “teach” Google Tag Manager to 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 than or equal to 3.

That’s it! You can now assign this trigger to any tag you want, whether it is a pop-up, Google Analytics event tag, or whatever. I’ll leave it entirely to your imagination.

 

Delete a Cookie

If you want to delete a particular 1st-party cookie, you need to set its expiration time to a date in the past, e.g., January 1st, 1970. 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 fields (in the 4th and 5th lines) empty and see if it works.

A

Few More Ideas

Here’s food for thought if you still don’t know how to leverage cookies in your marketing stack. 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 a unique affiliate ID). You can fetch that data from the URL, set it as a cookie, and send it 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 purchased a product 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 in cookies. Even if the user has logged out, you can still identify them 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

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 are accessible by JavaScript in your browser (including GTM).

If a cookie has a checkbox in the HttpOnly column, GTM cannot access its value. This means that a 1st party cookie variable will return undefined.

 

Working with cookies and Google Tag Manager: Final Words

It’s pretty easy to manage cookies with Google Tag Manager. First, you must fire a custom HTML tag that sets the cookie with a particular value (there are also custom templates available in Google Tag Manager’s gallery). 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 to fire a particular tag after 3 page views, or for those visitors who have visited a specific 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 for using cookies with Google Tag Manager? Let me know in the comments.

By the way, I’ve noticed some people asking me this 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.

Julius Fedorovicius
In Google Tag Manager Tips
52 COMMENTS
Mayo Racek
  • May 19 2017
  • Reply

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

    Mayo Racek
    • May 19 2017
    • Reply

    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

    Julius Fedorovicius
    • May 19 2017
    • Reply

    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?

Scott Sunderland
  • Jul 6 2017
  • Reply

This is glorious. Great work Julius!

Margaret White
  • Feb 13 2018
  • Reply

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!

    Julius Fed
    • Feb 13 2018
    • Reply

    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.

Baldwin
  • Apr 19 2018
  • Reply

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?

    Julius Fed
    • Apr 20 2018
    • Reply

    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).

Drew Warren
  • Jun 25 2018
  • Reply

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.

    Julius Fed (Fedorovicius)
    • Jun 26 2018
    • Reply

    Hey, here's the guide that can help you https://www.analyticsmania.com/post/track-affiliate-sales-with-google-tag-manager-and-google-analytics/

Luca
  • Jul 10 2019
  • Reply

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!

    Julius Fedorovicius
    • Jul 11 2019
    • Reply

    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.

Mark
  • Feb 24 2020
  • Reply

Thanks for this Julius!
How can I make sure these cookies fire domain1.com and also on domain2.com?

    Julius Fedorovicius
    • Feb 25 2020
    • Reply

    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)

tim
  • Apr 15 2020
  • Reply

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

    Julius Fedorovicius
    • Apr 15 2020
    • Reply

    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.

Joe
  • Jul 20 2020
  • Reply

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>

Kelly
  • Oct 6 2020
  • Reply

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?

    Julius
    • Oct 7 2020
    • Reply

    Either your cookie variable contains an incorrect name or you are trying to access httponly cookie, which cannot be accessed by Javascript (including GTM).

Tom
  • Oct 29 2020
  • Reply

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!

Shashank Mangal
  • Nov 17 2020
  • Reply

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,

    Julius Fedorovicius
    • Nov 17 2020
    • Reply

    What if I go to another page before the conversion? your gclid parameter will no longer be in the URL

Inge
  • Nov 18 2020
  • Reply

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!

    Julius Fedorovicius
    • Nov 18 2020
    • Reply

    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.

      Inge
      • Nov 27 2020
      • Reply

      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!

Usman
  • Dec 27 2020
  • Reply

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?

Tom
  • Jan 9 2021
  • Reply

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!

    Julius Fedorovicius
    • Jan 9 2021
    • Reply

    Hi, cookies are not shared between devices

David
  • Nov 1 2021
  • Reply

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.

    Julius Fedorovicius
    • Nov 5 2021
    • Reply

    Hi, read this https://www.analyticsmania.com/post/annoy-email-subscribers-less-with-google-tag-manager/

Mark
  • Dec 30 2021
  • Reply

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.

    Julius Fedorovicius
    • Jan 4 2022
    • Reply

    You must set a cookie on .yourdomain.com (with a dot in front of it)

marcha
  • Mar 22 2022
  • Reply

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?

Walter
  • Mar 22 2022
  • Reply

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

    Julius Fedorovicius
    • Mar 22 2022
    • Reply

    If IP is constantly changing then cookie is a viable option

Anna
  • Sep 28 2022
  • Reply

Hello Julius! Thanks for this very helpful article!
I have a question: if my cookieValue is not a boolean but a string, what should I type in the code? I have a cookie that passes unique customers' IDs after they log in. So the value differs for each user. How should I approach this?

Thanks in advance for your answer!

Will Baltazar
  • Jan 19 2023
  • Reply

Can you provide guidance towards excluding a cookie from event tracking? For example, I would like to exclude my own page visits on the page_view event. I know what my cookie id is.

Super Tech Hero
  • May 17 2023
  • Reply

Hi! How do I set the var cookieValue = "true";

instead of "true", I want it to pass along a query string value

let's say I have mysite.org?mcid=11
I have it set for the customHTML tag to fire only when there is an mcid. So thats great!
That being said, I want the cookie to contain the value of 11 rather than "true". Do you know the adjustments to the script for that?

    Super Tech Hero
    • May 17 2023
    • Reply

    figured it out!
    Adjusted your code a bit:

    <script>
    (function(){
    var cookieName = "mcidcookie"; // Name of your cookie
    var urlParams = new URLSearchParams(window.location.search);
    var myParam = urlParams.get('mcid');
    var cookieValue = myParam; // Value of your cookie, in this case to be all of query
    var expirationTime = 172800; // Two days 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>

Erik
  • Mar 27 2024
  • Reply

Hi!

Do you have any solution how to get the landing page and the utm-parameters from new users (have not accepted/denied cookies earlier)? Now I only get data after consent. So I am missing the landing page and the utm-parameters.

Regards
Erik

    Julius Fedorovicius
    • Mar 27 2024
    • Reply

    Make your consent popup block the website content on the landing page. If visitors give consent, you will still see their UTM data in your GA4 property.

Dawn
  • Jul 12 2024
  • Reply

I want to track the number of users using "Total Users" metric, however it shows data inconsistency.

When I checked the psuedo user ID in Big Query, there are some cookie ID that are the same but with different number/volume of "GA1.1" (Please sample below).

e.g:
1. GA1.1.GA1.1.GA1.1.GA1.1.GA1.1.GA1.1.GA1.1.GA1.1.GA1.1.136574941.1719825041
2. GA1.1.GA1.1.GA1.1.GA1.1.GA1.1.136574941.1719825041
3. GA1.1.GA1.1.136574941.1719825041

This cookie ID should be counted as 1 user, however GA4 counted as 3 different users.

    Julius Fedorovicius
    • Jul 12 2024
    • Reply

    Sounds like something in your setup is messing up with the client_id. Usually this happens when something in the tracking code/GA4 tags sets the client_id parameter. See if that's your case

Sandeep
  • Jul 17 2024
  • Reply

Hi Julius

in my site _gcl_au cookie is not secure which causing us issue is there nay way that we can make it secure using GTM? Pls reply

Serge
  • Oct 31 2024
  • Reply

Hi Julius,
IMO using cookies for the page view count isn't appropriated as you send it with each requests to your website and is is not used. I'd rather use localStorage for that. Limitation is that localStorage isn't shared between subdomains. There is no expiration on localStorage either but that can be implemented easily.

Dave
  • Dec 13 2024
  • Reply

EditThisCookie extension is not in the Chrome store anymore. Do you recommend any other options?

    Julius Fedorovicius
    • Jan 2 2025
    • Reply

    Here you go https://chromewebstore.google.com/detail/editthiscookie%C2%AE/hlgpnddmgbhkmilmcnejaibhmoiljhhb

Dave
  • Dec 16 2024
  • Reply

I have set it up as described for a Google Ads click.... but how do I then use that info?

I am trying to set the cookie so that it can be used by my CRM (High Level) to match up a phone call dialled from a click on our website from a previous Google Ads visitor.

How do I somehow get the cookie being present to trigger my CRM?

Dave
  • Dec 16 2024
  • Reply

How would I pass the gclid to the cookie as the cookie value. That way I can use that to track which ads a client clicked on.

Mike Myers
  • Jan 13 2025
  • Reply

I was hoping for a way to delete cookies that track all my stuff without me know how it got there. I'm not a programmer just a casual user, but it's starting to get really annoying?

Jati
  • Feb 13 2025
  • Reply

Hi Julius. I'm curious about how to implement this method in an IFrame format. Specifically, how can the IFrame retrieve UTM parameters from its parent page or site if they belong to different domains? Any thoughts?

larry
  • Jun 19 2025
  • Reply

Hi, if we have a custom HTML tag that fires to place a cookie in a Client/WebGTM and we are using the Stape sGTM soluion, will the cookie be durable because the client fires the javascript and points to my server endpoint?

Leave a comment Cancel reply

Your email address will not be published. Required fields are marked *


 

Hi, I'm Julius Fedorovicius and I'm here to help you learn Google Tag Manager and Google Analytics. Join thousands of other digital marketers and digital analysts in this exciting journey. Read more
Analytics Mania
  • Google Tag Manager Courses
  • Google Tag Manager Recipes
  • Google Tag Manager Resources
  • Google Tag Manager Community
  • Login to courses
Follow Analytics Mania
  • Subscribe to newsletter
Recent Posts
  • Google Tag Manager Server-Side Tagging with Stape
  • How to Preserve Ad Click IDs with Server-side Tagging
  • LinkedIn Conversions API with Google Tag Manager. The Guide.
Analytics Mania - Google Tag Manager and Google Analytics Blog | Privacy Policy
Manage Cookie Settings