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

Evan picture Evan · Apr 15, 2011 · Viewed 224.5k times · Source

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>

Answer

aroth picture aroth · Apr 15, 2011

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>