Sunday, October 16, 2011

Hey ma'am, where are my cookies?


I recently made some big changes to a content management system I built for one of my clients about 5 years ago. I worked on the site's SEO, enabled clean URLs via .htaccess files because the CMS wasn't built with MVC where there would probably have being a main controller that routes requests to others.

The problem started after I had added all the necessary pages but spent the next few days worrying about a bug in one of my scripts, as the cookies added on some pages of the site do not propagate to other pages. Looking through Chrome Developer Tools and Firefox's Firebug, I could see all the cookies, but when I fetch the cookies via document.cookie, I only get to see some of the cookies and not all. I wondered why a script that was perfectly working before changes to it's routing stopped working. I spent several days modifying my script that manages cookies only to discover after almost a week of battling with it that you should think twice before leaving the path property of a cookie blank when creating it.

When you leave the path property of a cookie blank, it means that only websites in that domain (including the path) that set the cookie can retrieve it. For example, if you create a cookie on the page www.mywebsite.com/books and left the path property blank, it wouldn't be accessible from www.mywebsite.com/novels because the path for the created cookies are /books but you are trying to access it from /novels. So, to avoid unnecessary headache while managing cookies in your application or on your website, ensure that you set the path to the root .i.e. '/', instead of leaving it blank if you want it to be accessible from all paths within that domain.

The culprit in my case was:
document.cookie = name + "=" + escape (value) +
        ((expires) ? "; expires=" + expires : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");

but I eventually overcame the problem by modifying the path of any created cookies to be '/' instead of leaving it blank as obtainable above.
document.cookie = name + "=" + escape (value) +
        ((expires) ? "; expires=" + expires : "") +
        ((path) ? "; path=" + path : "/") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");

This StackOverflow answer saved my ass . You can read more about cookies here.

No comments: