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.

Background

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

4 comments on “jQuery Cookie problem – persistence and duplication”

  1. You saved the day!!! I’ve been searching a fix for this for the past 3 hrs..thanks…great post!

  2. I am using Same thing… But in My web Application it is not Fixed from where the Cookie will Be Set, So is there any way that From Starting i can store it at Application Domain.. ?

  3. Awesome!!!, Thanks a lot for explanation. Minor details matter a lot. I was having similar issues and it got fixed after i set the path.

Add your comment

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>