Sharing cookies between different domains

Pradeep Moolemane
Nggawe Nirman Tech Blog
2 min readJul 5, 2020

I am writing this story to give an insight on how we can enable cookies sharing between the two different domains.

Cookies are small piece of information sent by website and stored on client’s machines using web browser. These cookies are stored to remember stateful information about the user activity. More information here

Domain is used to identify the network domain or represent the IP resource internet. More information here

As we know that cookie set by one domain cannot be accessed by the another domain. But cookie set to main domain can be accessed by subdomains.

Example: Cookie set to domain “maindomain.com” can be accessed by any sub domain of main domain, that is subdomain.maindomain.com, anysub.maindomain.com. but vice verse not possible.

Cookie sharing can happens only if the domain is explicitly named in the Set-Cookie header as shown below:

Set-Cookie: name=value; domain=maindomain.com

That being said above, can we share the cookie between two different domains ? for example mydomain.com and yourdomain.com

Yes, there are different ways where you can allow cookie set by one domain use/read by other domains, such are encoding cookie into url.

Here i talk about xhrFields withCredentials = true approach which enables sharing the credentials such as cookies, authorized headers between different domains.

var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://yourdomain.com/', true);
xhr.withCredentials = true;
xhr.send(null);

Different domain cookie obtained by the withCredentials = true will still honor the same-origin policy and hence can not be read by the requesting script through document.cookie or from response header.

And with this, it ensure that credentials shared with known domain by forcing to set Allowed Origin to single domain. Never allow CORS setting to *.

This has no effect on same-origin request.

--

--