717

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?

5
  • 3
    Yes you can.. please see link below codeguru.com/csharp/csharp/cs_internet/article.php/c19417/…
    – Rahul Jain
    Sep 23, 2013 at 22:08
  • 1
    Closely related: stackoverflow.com/questions/3089199/… Nov 10, 2014 at 8:17
  • 2
    can you please look at this question stackoverflow.com/questions/38351769/… Jul 14, 2016 at 4:22
  • 1
    @adam0101 What if domain and sub domain are hosted on different server ? Dec 9, 2016 at 15:48
  • 11
    @user3782114, it doesn't matter if they are on different servers. In my case, they were not only on different servers, but each domain was load-balanced across multiple servers. One thing that did trip us up a bit was that the lower environments (dev, test, uat, etc) started sharing the same cookie too once we did this because we had named them like "dev.oursite.com", "test.oursite.com", etc.. The trick there (at least in .Net) is to have a separate machine key generated for each environment and save that in your Web.config (assuming you transform the config for each environment).
    – adam0101
    Dec 12, 2016 at 2:19

7 Answers 7

1093

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 "parent" 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 example.com and any subdomain of example.com, including nested subdomains like subsub.subdomain.example.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.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.

33
  • 3
    I don't understand why you wouldn't just put the leading "." on the domain for maximum compatibility with old and new Dec 21, 2015 at 8:56
  • 48
    In the old standard, a cookie with domain=.mydomain.com is not valid for the bare mydomain.com, so the two RFCs are not compatible with each other.
    – cmbuckley
    Dec 21, 2015 at 9:27
  • 6
    @Frank, yes I know. My comment was to clarify that my question was regarding sharing cookies between a domain and a subdomain, NOT between two subdomains.
    – adam0101
    Feb 12, 2018 at 16:43
  • 4
    @shi Yes - please see the last sentence: "This can also be used to allow sub1.mydomain.com and sub2.mydomain.com to share cookies."
    – cmbuckley
    Jun 12, 2019 at 17:47
  • 15
    I am not sure where to put this so I am choosing the comments of the accepted answer. It took long time and failed experiments to prove the above on my localhost, until it occurred to me that I should call the localhost with a dot in the name. Like "localhost.com" or something like that. Then all the "set cookies" behaviours started following the explanations written here in this answer. Hoping this might help somebody.
    – Cesc
    Mar 20, 2020 at 16:31
146

Please everyone note that you can set a cookie from a subdomain on a domain.

(sent in the response for requesting subdomain.example.com)

Set-Cookie: name=value; Domain=example.com // GOOD

But you can't set a cookie from a domain on a subdomain.

(sent in the response for requesting example.com)

Set-Cookie: name=value; Domain=subdomain.example.com // Browser rejects cookie

Why?

According to the specifications, RFC 6265 section 5.3.6 Storage Model,

If the canonicalized request-host does not domain-match the domain-attribute: Ignore the cookie entirely and abort these steps.

and RFC 6265 section 5.1.3 Domain Matching,

Domain Matching

A string domain-matches a given domain string if at least one of the following conditions hold:

  1. The domain string and the string are identical. (Note that both the domain string and the string will have been canonicalized to lower case at this point.)

  2. All of the following conditions hold:

  *  The domain string is a suffix of the string.

  *  The last character of the string that is not included in the
     domain string is a %x2E (".") character.

  *  The string is a host name (i.e., not an IP address).

So subdomain.example.com domain-matches example.com, but example.com does not domain-match subdomain.example.com

Check this answer also.

3
  • 4
    Thanks for providing a documented answer that gives the RFC refs explaining exactly when browsers are supposed to accept a cookie domain, and why it's okay for "foo.domain.com" to set a cookie for "domain.com", even though it seems it would violate the "same origin policy" and could be seen as a security risk.
    – odony
    Aug 12, 2020 at 14:24
  • this how i understand it and it works local setup but once I deploy to Test environment, then cookie no longer is being set unless i remove the domain attribute, please if you can have a look at my question here stackoverflow.com/questions/69865370/… Nov 6, 2021 at 15:51
  • 1
    It's worth pointing out that you can set a cookie on any superdomain up to but not including the TLD. So for instance you can't use domain=com. This is fairly obvious, but there are a list of domains that can't be used: publicsuffix.org
    – cmbuckley
    Nov 19, 2021 at 12:32
50

I'm not sure cmbuckley's answer is showing the full picture. What I read is:

Unless the cookie's attributes indicate otherwise, the cookie is returned only to the origin server (and not, for example, to any subdomains), and it expires at the end of the current session (as defined by the user agent). User agents ignore unrecognized cookie.

RFC 6265

Also

8.6.  Weak Integrity

   Cookies do not provide integrity guarantees for sibling domains (and
   their subdomains).  For example, consider foo.example.com and
   bar.example.com.  The foo.example.com server can set a cookie with a
   Domain attribute of "example.com" (possibly overwriting an existing
   "example.com" cookie set by bar.example.com), and the user agent will
   include that cookie in HTTP requests to bar.example.com.  In the
   worst case, bar.example.com will be unable to distinguish this cookie
   from a cookie it set itself.  The foo.example.com server might be
   able to leverage this ability to mount an attack against
   bar.example.com.

To me that means you can protect cookies from being read by subdomain/domain but cannot prevent writing cookies to the other domains. So somebody may rewrite your site cookies by controlling another subdomain visited by the same browser. Which might not be a big concern.

Awesome cookies test site provided by cmbuckley and for those that missed it in his answer like me; worth scrolling up.

5
  • 5
    That looks to agree with what I'm saying: unless you specify a domain, the cookie is only used for the request host. This means that Set-Cookie: name=value from mydomain.com won't be sent with requests to subdomains. Have a play with this test script too.
    – cmbuckley
    Jul 21, 2016 at 10:00
  • @cmbuckley, ok, what you said seems correct. I'll reword my answer. Thank you for pointing that out. Jul 21, 2016 at 22:14
  • Need to point out, that section 4.1.2 (first citation) is not normative...
    – Velda
    Jul 26, 2018 at 12:07
  • 1
    thanks for the cmbuckley link. nice to test how it works quickly.
    – Laurence
    Jan 21, 2019 at 14:50
  • 1
    Upvote for pointing out the test site again.
    – zylstra
    Apr 18, 2022 at 0:44
30

Here is an example using the DOM cookie API, so we can see the behavior for ourselves.

If we execute the following JavaScript code,

document.cookie = "key=value"

it appears to be the same as executing:

document.cookie = "key=value;domain=example.com"

The cookie key becomes available (only) on the domain example.com.


Now, if you execute the following JavaScript code on example.com,

document.cookie = "key=value;domain=.example.com"

the cookie key becomes available to example.com as well as subdomain.example.com.


Finally, if you were to try and execute the following on subdomain.example.com,

document.cookie = "key=value;domain=.example.com"

does the cookie key become available to subdomain.example.com? I was a bit surprised that this is allowed; I had assumed it would be a security violation for a subdomain to be able to set a cookie on a parent domain.

7
  • 2
    This makes me wonder if there are separate specs describing the behavior of httponly cookies versus the kind of cookies you are creating.
    – adam0101
    Sep 26, 2017 at 21:37
  • 4
    The docs you posted do not agree with the statements you make. The first 2 examples are not equivalent (a domain attribute causes the cookie to work on subdomains; no such attribute does not). Leading dots are ignored at best and actively blocked at worst.
    – cmbuckley
    Jan 11, 2018 at 20:44
  • this is the best solution if you don't want to rely on host headers. I checked it and its working
    – Szymon
    Aug 6, 2019 at 9:47
  • 1
    @zeroliu which browser did you test that on? That is not how it works in modern browsers. Test this at subdomain.setcookie.net
    – cmbuckley
    Nov 23, 2022 at 11:48
  • 1
    @NicolasLabrot as you say, that's how those browsers are choosing to show it in their dev tools - a leading dot just means it's not a host-only cookie. I find that EditThisCookie does a better job of displaying this.
    – cmbuckley
    Feb 15 at 16:34
7

Be careful if you are working on localhost! If you store your cookie in JavaScript like this:

document.cookie = "key=value;domain=localhost"

It might not be accessible to your subdomain, like sub.localhost. In order to solve this issue you need to use VirtualHost. For example, you can configure your virtual host with ServerName localhost.com, and then you will be able to store your cookie on your domain and subdomain like this:

document.cookie = "key=value;domain=localhost.com"
2
  • AHA! Maybe this is my issue.
    – Caio Mar
    Aug 2, 2020 at 11:20
  • 1
    On windows, you can just modify your hosts file and set whatever alias you want for localhost. For example, local.mydomain.com.
    – adam0101
    Sep 3, 2021 at 13:23
3

In both cases, yes, it can, and this is the default behaviour for both Internet Explorer and Edge.

The other answers add valuable insight, but they chiefly describe the behaviour in Chrome. It's important to note that the behaviour is completely different in Internet Explorer. CMBuckley's very helpful test script demonstrates that in (say) Chrome, the cookies are not shared between root and subdomains when no domain is specified.

However, the same test in Internet Explorer shows that they are shared. This Internet Explorer case is closer to the take-home description in CMBuckley's www-or-not-www link. I know this to be the case because we have a system that used different servicestack cookies on both the root and subdomain. It all worked fine until someone accessed it in Internet Explorer and the two systems fought over whose session cookie would win until we blew up the cache.

-1

I do this and it works for me:

Cookie.set('token', 'some jwt-token', { expire:50000, domain: 'example.com' })
1
  • 3
    How does that answer the question? - "Can example.com (without the www subdomain) access the cookie if created in subdomain.example.com?". E.g., where does the sub domain come in? Can you elaborate? What system was this tried on? Browser, actual website, what programming language (PHP? JavaScript?), in what environment (e.g., web framework), all incl. versions. Please respond by editing (changing) your answer, not here in comments (****** without ****** "Edit:", "Update:", or similar - the answer should appear as if it was written today) Dec 8, 2022 at 21:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.