How to set expiry date of a cookie (using jQuery Cookies plugin)

cookie

In a previous post I explained what is the process for Saving a complex JSON object in a cookie by using jQuery (demo included in PHP). Now, I would like to add some related information about how to set an expiry date of a cookie using the same plugin (jQuery Cookies).

First of all, it is important to know that an expire date is just a valid JavaScript Date Object, I mean, you will only need to create a date and then assign this to an array of options when you save your data in a cookie. Let me explain using a little example:

function setUserConfigInCookie(){
      var expireDate = new Date;
      expireDate.setDate(expireDate.getDate() + 7); // It expires in a week

      var options = {
        path: '/',
        expiresAt: expireDate
      }

      userConfig = {}; // This is a valid JSON object that you need to save in a cookie
      $.cookies.set( 'userConfig', userConfig, options);

      // console.log('Expires=' + expireDate.toGMTString());
    }

With this simple code we can save a cookie (complex JSON object) and set an expiry date (in this example the cookie is going to expire in a week). If you want to verify that all is working, you could search for your cookie in your favorite browser, for example next image uses Firefox to see this cookie:

expiry-date

That’s it at this moment.

Be happy with your code!

Alex Arriaga

2 comments on “How to set expiry date of a cookie (using jQuery Cookies plugin)”

Leave a Reply

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