Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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> 
like image 435
Evan Avatar asked Apr 15 '11 01:04

Evan


People also ask

Do cookies work across subdomains?

To share cookies across subdomains, you can simply create cookies with the domain directive set to the parent domain, in this case, example.com, rather than either of the specific subdomains.

Can subdomain read domain cookie?

That is, if the domain name in your cookie's domain parameter doesn't start with a period, then it will not let subdomains read that cookie. If it does start with the period, then all subdomains will have full access to that cookie's value.

Can cookies be read across domains?

Yes, there are different ways where you can allow cookie set by one domain use/read by other domains, such are encoding cookie into url. Here i talk about xhrFields withCredentials = true approach which enables sharing the credentials such as cookies, authorized headers between different domains.


2 Answers

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> 
like image 200
aroth Avatar answered Sep 24 '22 12:09

aroth


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).

like image 43
Mike Lewis Avatar answered Sep 24 '22 12:09

Mike Lewis