Search code examples
javascriptcookiesgoogle-tag-managerevent-tracking

Custom cookie not persistent through navigation


I set a cookie with the traffic referrer as a value. The cookie is supposed to be created only if the visit is from referrer and to be persistent through the session (expires after 1h).

However, the cookie is changing on every new page view.

  1. Incoming traffic from Google > cookie value = "google.com"
  2. New page view on site > cookie value = "my-site.com"

Isn't the cookie created supposed to be persistent until the expiring time ?

Here is the code creating the cookie :

document.cookie = "Referrer="+{{Referrer Domain}}+"; max-age=86400; path=/"

It is triggered if the page referrer is different from "my-site.com".

Note:

Using the Chrome console > Application, I noticed all cookies are set on the domain "my-site.com", And the cookie I created is set on the domain "www.my-site.com". Thus I guess by setting the cookie domain on the root domain it is going to persist properly....

How to set precisely the domain of the cookie ?


Solution

  • I solved this issue by adding the cookie domain manually :

    document.cookie = "Referrer="+{{Referrer Domain}}+"; max-age=86400; path=/; domain=my-site.com"
    

    Furthermore, the cookie was resetting on every page view... so I added a tag to check if the cookie already exists first:

    document.cookie.includes("Referrer")
    

    If it returns "false", then the cookie is created.