JavaScript's document.cookie does not replace cookie in the subdomain

2.4k views Asked by At

I'm having trouble setting cookies.

When I call document.cookies = "cookieName=cookieValue;path=/;domain=domain.com"; from a subdomain like "subdomain.domain.com", Chrome shows the cookie being set on both, the domain and the subdomain I'm in. This is not ideal, since I only want to set it on the domain, but for now it's fine with me.

The problem is when I want to replace the cookie. If I call the same line but with a different cookie value like document.cookies = "cookieName=cookieValue2;path=/;domain=domain.com";, Chrome shows the cookie getting replaced in the domain, but not the subdomain. This is a problem.

Can someone help me with this?

1

There are 1 answers

0
AudioBubble On BEST ANSWER

Well, not sure what's happening with this, but the work around I found was to simply set the cookie twice: one without specifying the domain (which replaces the subdomain cookie) and one for the domain:

document.cookies = "cookieName=cookieValue;path=/"; //Replaces the subdomain cookie
document.cookies = "cookieName=cookieValue;path=/;domain=domain.com"; //Replaces the domain cookie