How to write a value to a cookie using GTM
Guide
If there is a value stored in a variable (either as a Global JavaScript variable on a webpage or as a Variable within GTM) this can be written to a browser cookie using the following code using a Custom HTML tag:
<script>
(function (cookieName, cookieValue, expirationTime, domain) {
var date = new Date();
date.setTime(date.getTime() + expirationTime); // Sets expiration time (Time now + expiration time)
var expiry = date.toUTCString(); // Converts cookie expiry to UTC time string
document.cookie = cookieName+"="+cookieValue+"; expires="+expiry+"; path=/; domain="+domain+"; SameSite=None; Secure"; // Sets cookie in browser
return;
})(<MY_COOKIE_NAME>, <MY_COOKIE_VALUE>, <EXPIRY_IN_MILLISECONDS>, <DOMAIN>); // pass cookie arguments here
</script>
Code language: HTML, XML (xml)
Edit the placeholders in Line 9 with the 4 required arguments (as denoted by the placeholders in <ANGLED_BRACKETS>):
- cookieName: This is the name of the cookie that will be created. Only use alphanumeric US-ASCII characters.
- cookieValue: This will be the value that you want to set. This must be a string type and can take any US-ASCII characters excluding control characters, Whitespace, double quotes, comma, semicolon, and backslash.
- expirationTime: This is the cookie expiry time in milliseconds. This must be an integer type.
- domain: This is the domain that the cookie will be hosted on. For example, to set a cookie for the Measurelab website and all of it’s subdomains, use: “.measurelab.co.uk”
Attach the appropriate trigger to the tag to signify when the cookie should be set. Ensure that when the trigger is made that the value being set in the cookie is available. For example, if scraping a value off the webpage document, ensure that the tag is fired once the DOM is ready and the value/variable is defined.
Finally, test in Preview Mode and Publish.
Prerequisites
Edit access to a GTM Container and the necessary values in place to set the cookie.
Use cases
Ensuring a User ID that is set when a user logs in on a particular subdomain is available on another subdomain.