Cookies and port in host’s location

I’ve just discovered setting cookies with port number in domain does not sets cookie (at least in Flock).

Let’s assume we have Rails application web server (default on TCP 3000 port). And in JS we use to set cookie something similar to:


function setCookie(name, value, expires, path, domain, secure) {
    cookie= name + "=" + escape(value) +
        ((expires) ? "; expires=" + expires.toUTCString() : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
    document.cookie = cookie+";";
}

setCookie("rnsloc",
    map.getCenter().lat()+"-"+map.getCenter().lng()+ "-" +map.getZoom(),
    date,
    '/',
    location.host )

Well it does not sets cookie. Why? Using Firebug’s JS console it takes minutes to find out.

>>> document.cookie="rnsloc=test1; expires=Mon, 20 Nov 2006 14:16:53 GMT; path=/route; domain=192.168.1.1;"
"rnsloc=test1; expires=Mon, 20 Nov 2006 14:16:53 GMT; path=/route; domain=192.168.1.1;"

>>> document.cookie
"rnsloc=test1; _session_id=f9be28b6447cdf32979ff173dd30cd3d"

>>> document.cookie="rnsloc=test2; expires=Mon, 20 Nov 2006 14:16:53 GMT; path=/route; domain=192.168.1.1:3000;"
"rnsloc=test2; expires=Mon, 20 Nov 2006 14:16:53 GMT; path=/route; domain=192.168.1.1:3000;"

>>> document.cookie
"rnsloc=test1; _session_id=f9be28b6447cdf32979ff173dd30cd3d"

Well as You can see after adding port to host rnsloc value does not changes – setting cookie fails silently. Why it matters? Beacouse many examples show how to set cookie using location.host property. It happens that it contains port number if it is present in URL. So You need to use something like location.host.split(":")[0]. I hope it does never contain http:// or https:// header.

Join the Conversation

1 Comment

  1. Instead of location.host.split(“:”)[0] you might want to try location.hostname.

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.