jQuery Cookie problem – persistence and duplication

I’ve started to use cookies to maintain user state and the jQuery Cookie plugin provides simple functions to create, read and delete cookies. However, I came across a problem where state didn’t appear to be persisting and on viewing the cookie information, using the web developer toolbar, I had multiple versions of the same cookie.


When a cookie is created normally (without the plugin), its path will normally default to "/" meaning that the cookie is valid throughout the whole domain.

It means that should you want to, cookies can be set per directory and they will be valid to a certain set of pages, i.e. set the path of the cookie to "/help" and all your help pages will have access to that cookie but none of those pages in, for instance, /home.

The solution

The problem occurs because jQuery Cookie sets its defaut path as the path the user was at when the cookie was created. The developer must explicitly set the cookie’s path as "/" if top-level domain access is what they’re after.

Instead of a simple name, value pair:

$.cookie('the_cookie', 'the_value');

You will need the slightly less simple addition of an argument:

$.cookie('the_cookie', 'the_value', { path: "/" });

Further reading