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>
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.
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.
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.
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>
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
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With