Skip to content

Frequently Asked Questions

Fagner Brack edited this page Mar 10, 2017 · 22 revisions

Reference version: 2.0.4

How to make the cookie expire in less than a day?

JavaScript Cookie supports a Date instance to be passed in the expires attribute. That provides a lot of flexibility since a Date instance can specify any moment in time.

Take for example, when you want the cookie to expire 15 minutes from now:

var inFifteenMinutes = new Date(new Date().getTime() + 15 * 60 * 1000);
Cookies.set('foo', 'bar', {
    expires: inFifteenMinutes
});

Also, you can specify fractions to expire in half a day (12 hours):

var inHalfADay = 0.5;
Cookies.set('foo', 'bar', {
    expires: inHalfADay
});

Or in 30 minutes:

var in30Minutes = 1/48;
Cookies.set('foo', 'bar', {
    expires: in30Minutes
});

How to remove all cookies?

It's not possible to remove literally all cookies from the user's browser. Some of them might have been created with a separate domain or path attribute than the one the user is currently in or even created with the httpOnly attribute and therefore they might not be visible.

What it's possible is to try to remove all cookies that are visible to the user:

Object.keys(Cookies.get()).forEach(function(cookieName) {
  var neededAttributes = {
    // Here you pass the same attributes that were used when the cookie was created
    // and are required when removing the cookie
  };
  Cookies.remove(cookieName, neededAttributes);
});

How to extend or add a new plugin or functionality to the library?

js-cookie does not have an easy way to add plugins or to extend any of its functionality. And that's by design.

See this for additional information and why.