πŸͺ Interactive and easy cookies from your browser in javascript
JavaScript CSS HTML
Latest commit 94cfe9a Nov 16, 2016 Francisco Presencia Fandos Added npm to the docs

README.md

cookies.js Circle CI License MIT

Super simple cookie manipulation on the front-end using javascript:

cookies({ token: '42' });     // Set it
var token = cookies('token'); // Get it
cookies({ token: null });     // Eat it

Getting started

There are few ways to use cookies.js. The easiest one is to use unpkg.com CDN:

<script src="https://unpkg.com/cookiesjs@1"></script>

You can also install it with bower or NPM:

npm/bower install cookiesjs

Or just download cookies.min.js and use it locally: <script src="cookies.min.js"></script>

Write a cookie

A cookie is set with a simple object as the first parameter:

cookies({ token: '42' });

We make the assumption that you want a cookie instead of a session, so cookies.js will set the expiration to 100 days by default. Set cookies.expires = 0 as seen in the options to use session cookies

You can set as many cookies as you want at the same time:

cookies({ token: '42', question: 'the Ultimate Question' });

The example above would be the same as this:

cookies({ question: 'the Ultimate Question' });
cookies({ token: '42' });

You can also set complex data and it will be json-encoded saved and retrieved properly in a single cookie:

var userdata = { email: 'test@test.com', token: '42' };
cookies({ user: userdata });

The example above is different from this one. This one sets two cookies:

cookies({ email: 'test@test.com' });
cookies({ token: '42' });

It will also store numbers (instead of strings) because it uses json to encode them:

cookies({ token: 42 });
var token = cookies('token');
console.log(token === 42, token === '42');  // true false

Lastly, you can concatenate them as many times as you want:

cookies({ token: 42 })({ token: '42' });

Note that this library does not accept a two-parameter strings to set cookies like many other libraries to avoid confusion with the options:

// NOT VALID
cookies('token', '42');

Options

or continue to read a cookie

When using cookies you can pass a second parameter as options (shown here with the defaults):

cookies({ token: '42' }, {
  expires: 100 * 24 * 3600,     // The time to expire in seconds
  domain: false,                // The domain for the cookie
  path: '/',                    // The path for the cookie
  secure: https ? true : false  // Require the use of https
});

Or you could set any of the options globally for all the instances after being called:

cookies.expires = 100 * 24 * 3600;      // The time to expire in seconds
cookies.domain = false;                 // The domain for the cookie
cookies.path = '/';                     // The path for the cookie
cookies.secure = https ? true : false;  // Require the use of https

An explanation of them all:

  • expires: when the cookie will expire and be removed. It can be:
    • A positive int to set the number of seconds until expiration
    • A negative int to remove the cookie
    • A Date() instance with the date of expiration
    • 0, false or a falsy value to set a session cookie
  • domain: the domain where the cookie is applied.
  • path: the folder where the cookie will be available. Normally it's better to leave this empty.
  • secure: force the cookie to be retrieved through https. By default this is set to true when it's set in an https domain to avoid it being stolen if you later visit an http page on a public connection.

For instance, to set a cookie that expires in 24h you would do:

cookies({ shortlife: 42 }, { expires: 24 * 3600 });

To set two cookies with the same domain, you could do:

cookies({ same: '4', place: '2' }, { domain: '.example.com' });

But you can also set them to different domains:

cookies({ same: '4' }, { domain: '.example.com' });
cookies({ place: '2' }, { domain: 'sub.example.com' });

Advanced options

There are some advanced options that we don't recommend to change as you could have problems down the road, but if you know what you are doing go ahead.

cookies({ token: '42' }, {
  nulltoremove: true,       // Set the value of a cookie to null to remove it
  autojson: true,           // Encode and decode data structures with JSON
  autoencode: true,         // Encode to make it safe for url (RFC6265)
  encode: function(str){ return encodeURIComponent(str); },  // Function to encode it
  decode: function(str){ return decodeURIComponent(str); },  // Function to decode it
  error: function(error, data, opt) { throw new Error(error); }, // To handle errors
  fallback: false  // A method to use as a fallback if cookies don't work
});

Normally you'd want to change these options globally:

cookies.nulltoremove = true;
cookies.autojson = true;
cookies.autoencode = true;
cookies.encode = function(str){ return encodeURIComponent(str); };
cookies.decode = function(str){ return decodeURIComponent(str); };
cookies.error = function(error, data, opt) { throw new Error(error); };
cookies.fallback = false;

Few notes and warnings:

  • If you want to store a null value in a cookie you'll have to set up cookies.nulltoremove = false.
  • If you cancel cookies.autojson, be aware that objects will be stored literally as [object Object], arrays will be joined with , and numbers will become strings.
  • Changing cookies.autoencode or cookies.encode could contribute to stop making it RFC 6265 compliant.
  • The method cookies.fallback is probably buggy and totally recommended not to be used. It will be used as a proxy if the cookie itself fails

Read a cookie

To read a cookie you call the main function with a string, that is the key of the cookie that you want to read. Let's say that you want to read the cookie token

var token = cookies('token');

cookies.js automatically stores and retrieves the cookies with JSON and URI-encoded. You can disable this with the options autojson and autoencode as seen in the Advanced Options.

Set and read a cookie:

cookies({ token: '42' });
var token = cookies('token');
// token === '42'

You can set and read a cookie at the same time taking advantage of the concatenation:

var token = cookies({ token: '42' })('token');
// token === '42'

Remove a cookie

With the options by default, you can remove a cookie in few different ways:

cookies({ token: null });
cookies({ token: 'a' }, { expires: -10 });

So, let's write, remove and read a cookie:

cookies({ token: '42' });
cookies({ token: null });
var token = cookies('token');
// token === undefined

Examples

Let's do a typical (simplified) authentication flow:

var token = cookies('token');
var user;
if (token) {
  $.post('/user/auth', { token: token }, function(data){
    user = data;
  });
}

Or let's check if the user accepts cookies (European law):

if (!cookies('accepted')) {
  $('.cookie-box').show();
  $('.cookie-box .accept').click(function(){
    $('.cookie-box').hide();
    cookies({ accepted: true });
  });
}

Author and License

Created and maintained by Francisco Presencia under the MIT license.