on
376 words - 2 minutes to read
Cookies, domains and how misunderstanding a simple term led to hours of debugging
Our problem
It’s been a while since I’m working on a side project with Sophie, and it’s pretty cool, because we’re learning a ton of stuff about web development (especially since I’m not a web dev at all).
We have our production environment on www.toto.com (obviously, not the real domain name) with a few users, and we thought we need a preproduction to ensure everything was working properly before deploying in production, so we had JLB setting up a subdomain for us : preprod.toto.com (thank you JLB 🤍)
As any web project, we’re using 🍪 extensively, and we’ve ended up encountering unexpected behaviors because somehow, we were mixing up production and preproduction cookies.
So, before blaming anyone or any tech, we went through the doc, read it carefully, and concluded that the Domain
attribute should resolve our issue :
Host to which the cookie will be sent.
- If omitted, defaults to the host of the current document URL, not including subdomains.
- Contrary to earlier specifications, leading dots in domain names (.example.com) are ignored.
- Multiple hosts/domains values are not allowed, but if a domain is specified, then subdomains are always included.
This is when we got confused !
Our understanding:
- if we don’t set any domain, the cookie will be set on toto.com, but not on www.toto.com (so we didn’t bother trying this)
- if we set the
Domain
to toto.com, the cookie will be available on www.toto.com, but also on all its subdomains (including preprod.toto.com 😓).
Obviously, we’ve tried to set the domain to www.toto.com
and preprod.toto.com
but we got a very unfriendly error message :
Cookie “cookie-name” has been rejected for invalid domain.
The solution
Ok, so actually, when reading the word domain
, we were thinking about the domain in a registrar
sense, like my domain is toto.com
and that’s it !
Not at all newbies !! Here we’re talking about the domain of the current page, which is the whole string from the protocol (http
or https
) until (and excluding) the URL Path
.
Therefore, in our case, all we need was doing nothing !
If omitted defaults to the host of the current document URL
Meaning www.toto.com or preprod.toto.com.
Well, now with this strategy, let’s hope we don’t need to share cookies between domains 😇.