Share cookie between subdomain and domain

If you set a cookie like this:

Set-Cookie: name=value

then the cookie will only apply to the request domain, and will only be sent for requests to the exact same domain, not any other subdomains. (See What is a host only cookie?)

Two different domains (e.g. mydomain.com and subdomain.mydomain.com, or sub1.mydomain.com and sub2.mydomain.com) can only share cookies if the domain attribute is present in the header:

Set-Cookie: name=value; domain=mydomain.com

The domain attribute must “domain-match” the request URL for it to be valid, which basically means it must be the request domain or a super-domain. So this applies for both examples in the question, as well as sharing between two separate subdomains.

This cookie would then be sent for any subdomain of mydomain.com, including nested subdomains like subsub.subdomain.mydomain.com. (Bear in mind there are other attributes that could restrict the scope of the cookie and when it gets sent by the browser, like path or Secure).

Because of the way the domain-matching works, if you want sub1.mydomain.com and sub2.mydomain.com to share cookies, then you’ll also share them with sub3.mydomain.com.

See also:


A note on leading dots in domain attributes: In the early RFC 2109, only domains with a leading dot (domain=.mydomain.com) could be used across subdomains. But this could not be shared with the top-level domain, so what you ask was not possible in the older spec.

However, the newer specification RFC 6265 ignores any leading dot, meaning you can use the cookie on subdomains as well as the top-level domain.

Leave a Comment