Skip to content

Google Tag Manager Custom Template to grab the current Root domain Name

David Vallejo

It happened to me a lot of times that while working with cookies that for whatever the reason I didn’t remembered to add the domain name to the settings, or that I was not able to properly define the root domain.

If you ever have had the need to set a cookie to the main root domain for your current domain, to make a cookie available for all the place, that depending on your current domain it may not be just enough to split the current hostname, because we need to think on the TLDs ( top-level domains ), SDLs ( second-level domain ), ccTLD ( country code top-level domain ), having all these variables you may end not knowing where the root domain is, for example is we’re talking about a domain , we could check things by the numbers of characters on each level, but that would be also not as relialable as it would look at a first time.

Actually ,afaik, the only reliable way to check this is relying on a proper lookup table or database ( ).

Good thing on JavaScript is that we try grab the current hostname and start setting a cookie till it get’s actually set.

For example let’s say that we have , we would be doing the following:

Good thing is that now you can have this value available without needing to deal with any code, just import the following Custom Variable to your containers 🙂

Available on GTM Gallery or via GitHub: