
January 21, 2019
Fire a tag only on the first page view with Google Tag Manager
Recently, I’ve received a question from one of my readers asking how can he fire a tag only on the first page view. What’s a use case for that? Situations may vary but that reader mentioned firing tags of ad-networks for the purpose of remarketing or running time-sensitive campaigns. For example, he wants to show ads of a different remarketing campaign when 7 days pass after the first page view (or the first event). However, he’s not sure how to track that first event. I’m not sure what kind of ad-network is that reader using, however, the case is understandable and it is not that hard to achieve, after all.

Time to use cookies
First of all, what are cookies? Simply put, cookies are small pieces of information that websites store on your computer. Cookies only contain bits of text, not anything else. The text can be a user ID, session ID, or any other text. If a website stored a cookie on your browser with some ID and, after a while, you returned, that cookie helps the website to identify that you are the same visitor.
Cookies can also store some less personal information, e.g. the number of pages viewed with that particular browser. And that’s exactly what we’ll do here today.
In one of my previous guides, I’ve explained how you can set, edit, and delete cookies with Google Tag Manager. If you haven’t yet, go definitely check it out.
So if there’s something you’ll find confusing in today’s blog post, go and read the aforementioned cookie guide. P.S. It’s also worth mentioning that in addition to cookies, you can also use Web Storage API in GTM. Simo Ahava has posted a guide about it.
Here’s the plan:
- When a visitor lands on a page (any page of your website where GTM container is implemented), a JavaScript code will fire.
- That code sets the cookie containing the number of how many page views has the visitor done (in general). That number is not limited to a single session. If a visitor on the 1st day makes 5 page views and returns after a month, the number of page views (in that cookie) will change to 6 (if, of course, that cookie is still present in a browser).
- With Google Tag Manager, we’ll read the value of the cookie and use it in triggers.
The script
Here’s the code that will increment the number of page views (stored in a cookie) every time a page is loaded (doesn’t matter whether the pages are different or whether a visitor is just hitting Refresh on the same page.
<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>
By default, this cookie is valid for 30 days. If you want to modify this setting, edit the number in the 37th line of the code.
setCookie("pageviewCount", pageviewCount, 30); //30 means that the cookie is valid for 30 days
The name of the cookie will be pageviewCount.
Add the aforementioned script to the Custom HTML tag in GTM and fire on All Pages. After that, go to Variables and create a new 1st Party Cookie variable with the following settings:
It will return the number of page views that is stored in that cookie.
Now, it’s time to test. Enable the Preview and Debug mode and refresh the page what you’re working on. Click an event you’re interested in and switch to the Variables tab. Take a closer look at the cookie – pageview count. It should contain “1”. Refresh the page and check the variable once again. This time, it should contain “2”. That’s because the Custom JavaScript (that we added to the Custom HTML tag) is looking for a cookie named pageviewCount and if it finds one, it increments its value by one.
If the value of the 1st Party Cookie Variable is undefined, please check whether your Custom HTML tag has fired properly and whether you entered the correct cookie name in variable’s settings (it is case-sensitive. Only pageviewCount with the uppercase C will work).
While testing, you can delete that cookie (thus start the counter from 0) by going to your browser’s cookie list and deleting it. I’m using Chrome so I can do that by going to Menu (Three dots) > More Tools > Developer Tools > Application > Cookies and find the pageviewCount cookie. Click it and hit the DELETE button on your keyboard.
Update the trigger
Let’s go back to the main case mentioned at the very beginning of this post, how to fire a tag only on the first page view. I presume that you already have a certain trigger in mind (it might be a Page View, a Click, or anything else). Open that trigger and add an additional condition:
{{cookie – page view }} Matches a Regex (ignore case) 1|undefined
This means that if a cookie contains “1” (meaning that’s the first page view) or if the cookie was not created yet (due to race conditions), that trigger will activate (of course, other trigger conditions must also be met).
Don’t limit yourself just with this case
With this JavaScript, you can also set tags to fire not only on the first page view but also only on the 2nd, 3rd, etc. It’s all up to you and your business case. For that purpose, I’ve created a GTM Recipe that can activate a tag on the 3rd page view and onwards.
Final words
And that’s the end of this quite short guide where you learned how to use cookies in order to fire a tag only on the first page view. In fact, it was not necessary to use this full script that counts page views. You could have just created a cookie called moreThanOnePageViews and set its value to true after the initial page view. If that cookie’s value equals to false, then your tag should fire. If the value is true, this means that a visitor has made more than one page view on your website.
Honestly, I chose the pageviewCounter solution here because I wanted to show you what other stuff you can do with cookies.
But let’s not limit yourself just with this guide. Feel free to check other solutions to fetch more ideas:
- Store User ID in a cookie
- Store Affiliate ID in a cookie
- Store the campaign information (a solution by Bounteous)
- Store the visitor’s consent data to be tracked, etc.
Have more questions? Feel free to contact me via social channels or just post a question below.

18 COMMENTS
PLEASS HELp me with how to fetch user id and it's location from JavaScript code using GTM
Hey, read this https://www.analyticsmania.com/post/google-analytics-user-id-with-google-tag-manager/
Nice work! Many thanks for sharing!
Hey, Julius,
Great work! If I want to segment a user, who for example read my 2 or more blog posts, what I have to do:
cookie = 2
&
path contains/blog
?
Hi Julius,
Thanks for sharing this amazing tutorial. Is there any way to achieve the same in mobile apps
Sorry, I don't work with mobile apps thus I cannot give you a tip/solution.
Hi, I work for a newspaper My boss want I push adsnetwork code through GTM.How can I set ads code fire only in article page, and split destop and mobile?
Do you provide consulting services? We just need help with this solution above. WE use google tag manager and facebook is double counting conversions.
How would I set this cookie to only fire on the first page of a session?
Do I just remove the expiration?
If you are talking about the Google Analytics session, then it is practically impossible to replicate the GA session in the frontend of your website and make it 100% precise. There are many things that can affect visitor's session in GA, not just 30 minutes duration or new traffic source.
But if you are ok with less than 100% accuracy (I don't know what is the real accuracy of this), you could employ something like this https://www.bounteous.com/insights/2017/12/18/utmz-cookie-replicator-gtm/
Hello, how can I fire a tag only the first page view for a specific page?
Update the trigger. Of the custom html tag. Fire it only on that specific page.
Thanks. My problem is that on the first page view the value "undefined", and on the second page view the value is "1". So the event fires twice. How can I work around this?
So if the first pageview is undefined, enter this as a condition in your trigger. If undefined, then this is a first pageview in your case. All other numbers mean that this is not a first pageview.
How can i set it on first page view two different pages? for example, i want it to fire on the first page view of page X and as well as first page view of page y?
Hello Julius,
I'm using a Visibility Trigger and I want to fire this event only 1 time, the first time the user sees a specific text. I don't want to fire multiple events if the users sees the same text more than one time.
With the activators available (once per page, once per element, fire every time) none of these options work for me, because I just want it to fire the first time the user sees the content.
Do you know how can we solve this?
You will need to work with cookies. If a visitor sees the text, set a cookie. And then use the cookie as a part of your blocking condition in the trigger.