Question:
There is a domain example.com
There is a subdomain subdomain.example.com
When I set cookies from JS, explicitly specifying domain=example.com
, they automatically appear on subdomain.example.com
.
Only MS Edge has this behavior. Does anyone know what's the matter here?
Answer:
It's just a feature of the domain matching mechanism in different browsers.
Edge appears to follow the current Proposed Standard, RFC6265 from 2011. It contains the following rules for checking domains:
5.1.3. Domain Matching
A string domain-matches a given domain string if at least one of
the following conditions hold:o 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.)o 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).
Those. a cookie set with an explicit domain name is always available on the subdomain. And that's okay.
Cookies for which no domain has been specified are set with the host-only-flag, which restricts their availability to the current domain only (no subdomains).
Not so modern browsers try to follow the outdated RFC2965 from 2000, in which the check looked a little trickier:
Host A’s name domain-matches host B’s if
* their host name strings string-compare equal; or * A is a HDN string and has the form NB, where N is a non-empty name string, B has the form .B', and B' is a HDN string. (So, x.y.com domain-matches .Y.com but not Y.com.)
Those. subdomains saw cookies from the main domain only if the cookie's domain value started with a dot.
The trick was that the browser was required to add a dot to the domain value.
If an explicitly specified value does not start with a dot, the user agent supplies a leading dot.
but only if the domain was set via the Set-Cookie header.
If the domain was not explicitly set, then the cookie was placed on the domain without . at the beginning, and was not available to subdomains. What brought the funniest bugs in Chrome, when a cookie on the client was set simultaneously with a dot and without a dot, and it was impossible to remove it from the server.
The case of setting cookies via document.cookie
was not covered by the standard. Some browsers (IE/Edge) add a dot automatically. Some – expect you to add it before domain manually.
In any case, RFC2965 is outdated, so sooner or later all cookies will be visible to subdomains. There is a link to developer.mozilla.org in the adjacent answer, and even there it already says
Contrary to earlier specifications, leading dots in domain names are ignored. If a domain is specified, subdomains are always included.