3

Is it possible to store a JS cookie for the current domain including subdomains.

e.g.: document.cookie = "key=value; expires=Tue, 16 Apr 2019 11:31:56 GMT; path=/;secure" sets a cookie for the current domain but does not add a dot to the domain name.

I know that it is possible to specify the domain via domain=.example.com but I do not want to hardcode the domain name.

I tried something like this but it did not work out: document.cookie = "key=value; expires=Tue, 16 Apr 2019 11:31:56 GMT; path=/;secure;domain=."

Update:

I know you can get the current domain with window.location.hostname but is there a solution where i do not need to get the domain name programmatically

UPDATE 2:

like described here: What does the dot prefix in the cookie domain mean?

The leading dot means that the cookie is valid for subdomains as well; nevertheless recent HTTP specifications (RFC 6265) changed this rule so modern browsers should not care about the leading dot. The dot may be needed by old browser implementing the deprecated RFC 2109.

This means that it does not make a difference if you use a dot before the domain name in modern browsers. That said, you can leave the domain section of the JS cookie blank and it is set to the current domain (which also matches subdomains)

warch
  • 2,387
  • 2
  • 26
  • 43

1 Answers1

4

Possible solution:

var domainName = window.location.hostname;
document.cookie = "key=value; expires=Tue, 16 Apr 2019 11:31:56 GMT; path=/; secure; domain=." + domainName;
warch
  • 2,387
  • 2
  • 26
  • 43
  • If not specified, defaults to the host portion of the current document location (but not including subdomains). Contrary to earlier specifications, leading dots in domain names are ignored, but browsers may decline to set the cookie containing such dot . If a domain is specified, subdomains are always included. [source: developer.mozilla.org] – Philipp Mochine Jun 13 '20 at 06:46