httpcookiessubdomain

Share cookies between subdomain and domain


I have two questions. I understand that if I specify the domain as .example.com (with the leading dot) in the cookie that all subdomains can share a cookie.

Can subdomain.example.com access a cookie created in example.com (without the www subdomain)?

Can example.com (without the www subdomain) access the cookie if created in subdomain.example.com?


Solution

  • 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. example.com and subdomain.example.com, or sub1.example.com and sub2.example.com) can only share cookies if the domain attribute is present in the header:

    Set-Cookie: name=value; domain=example.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 superdomain (i.e. further up the domain hierarchy). So this applies for both examples in the question, as well as sharing between two separate subdomains.

    This cookie would then be sent for example.com and any subdomain of example.com, including nested subdomains like subsub.subdomain.example.com. The same domain-matching logic is used to decide whether to send the cookie. (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.example.com and sub2.example.com to share cookies, then you'll also share them with sub3.example.com.

    See also:


    A note on leading dots in domain attributes: In the early RFC 2109, only domains with a leading dot (domain=.example.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. Some browsers will show a leading dot in developer tools to differentiate between host-only cookies and other cookies, but this is for display purposes only.