Creating a JavaScript cookie on a domain and reading it across sub domains

JavascriptCookies

Javascript Problem Overview


Below is a JavaScript cookie that is written on the user's computer for 12 months.

After we set the cookie on our main domain such as example.com, should the user visit a subdomain like test.example.com, we need to continue to identify the activity of the user across our "test" subdomain.

But with the current code, as soon as they leave www.example.com and visit test.example.com, they are no longer flagged as "HelloWorld".

Would anyone be able to help with my code to allow the cookie to be read across subdomains?

<script type="text/javascript">
  var cookieName = 'HelloWorld';
  var cookieValue = 'HelloWorld';
  var myDate = new Date();
  myDate.setMonth(myDate.getMonth() + 12);
  document.cookie = cookieName +"=" + cookieValue + ";expires=" + myDate;
</script>

Javascript Solutions


Solution 1 - Javascript

Just set the domain and path attributes on your cookie, like:

<script type="text/javascript">
var cookieName = 'HelloWorld';
var cookieValue = 'HelloWorld';
var myDate = new Date();
myDate.setMonth(myDate.getMonth() + 12);
document.cookie = cookieName +"=" + cookieValue + ";expires=" + myDate 
                  + ";domain=.example.com;path=/";
</script>

Solution 2 - Javascript

You want:

document.cookie = cookieName +"=" + cookieValue + ";domain=.example.com;path=/;expires=" + myDate;

As per the RFC 2109, to have a cookie available to all subdomains, you must put a . in front of your domain.

Setting the path=/ will have the cookie be available within the entire specified domain(aka .example.com).

Solution 3 - Javascript

Here is a working example :

document.cookie = "testCookie=cookieval; domain=." + 
location.hostname.split('.').reverse()[1] + "." + 
location.hostname.split('.').reverse()[0] + "; path=/"

This is a generic solution that takes the root domain from the location object and sets the cookie. The reversing is because you don't know how many subdomains you have if any.

Solution 4 - Javascript

You can also use the Cookies API and do:

browser.cookies.set({
  url: 'example.com',
  name: 'HelloWorld',
  value: 'HelloWorld',
  expirationDate: myDate
}

MDN Set() Method Documentation

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionEvanView Question on Stackoverflow
Solution 1 - JavascriptarothView Answer on Stackoverflow
Solution 2 - JavascriptMike LewisView Answer on Stackoverflow
Solution 3 - JavascriptcaseyjustusView Answer on Stackoverflow
Solution 4 - JavascriptrebagliatteView Answer on Stackoverflow