[Answered ]-Cookie collision: is it possible to distinguish between parent domain and subdomain cookies in Django and Javascript?

1👍

Since you say the websites are supposed to be completely independent the 3rd solution you propose seems most sensible. You should not be setting cookies in such a way that they are accessible by subdomains. Currently you are specifying the domain in the cookie, you should be skipping the domain which would mean the cookie would only be sent for the current domain (At least in modern browsers, IE does not follow this specification). If a domain is specified in the cookie it means that the cookie would also be used for the subdomains.

As mentioned in RFC 6265 – section 4.1.2.3:

If the server omits the Domain attribute, the user agent will return
the cookie only to the origin server.

Hence your cookie setting function should be like the following:

function setCookie(cname, cvalue, exdays) {
  // Domain should not be set unless cookie needs to be accessed by subdomains
  // var domain = window.location.hostname;


  if (exdays > 7) exdays = 7; // max in Safari

  var d = new Date();
  d.setTime(d.getTime() + (exdays*24*60*60*1000));

  var name = cname + '=' + cvalue + '; ';
  var expy = 'expires=' + d.toUTCString(); + '; ';
  // Domain should not be set unless cookie needs to be accessed by subdomains
  // var domn = '; domain=' + domain + '; ';
  var path = 'path=/; ';
  var secu = 'samesite=lax; secure;';

  var complete = name + expy + path + secu;
  document.cookie = complete;
}

0👍

As a temporary fix, I added some code to my setCookie function:

  var domain = window.location.hostname;
  deleteParentCookieIfNecessary(name, domain);

deleteParentCookieIfNecessary contains:

function deleteParentCookieIfNecessary(name, domain){
  var parts = domain.split('.');
  if (parts.length > 2){ // on subdomain
    var domain = parts.slice(-2).join('.');
    document.cookie = cname + '=;domain=.' + domain + ';path=/;max-age=0';
  }
}

The result is that when the cookie is set, if the url is a subdomain then the parent-domain’s cookie of the same name will be automatically deleted.

Leave a comment