Cookies in Javascript

published on May 3, 2012 in technical

I am back to using cookies in javascript again, so here is a little write-up about how to do that wit cookie.js

1. Usage

You may download cookie.js from github, here: https://github.com/js-coder/cookie.js

As always, it is recommended to use the minified version in production environment.

Then, embed it into your site like this:

<script src="cookie.min.js"></script>

2. cookie.set()

You may set one value at once

cookie.set('key', 'value');

or you may set multiple values at once:

cookie.set({
	key1: 'value1',
	key2: 'value2'
});

You may set the expiry like this:

cookie.set({
	key1: 'value1',
	key2: 'value2',
	{
	        expires: 7 // expires in 7 days
	}
})

3. cookie.get()

You may get one key's value, where the returned value is a string:

cookie.get("key");

or you may get multiple keys at once, where the returned value is always an object:

cookie.get(['key1', 'key2']);

4. cookie.all()

If you need to retrieve all the cookies, just do this:

var cookies = cookie.all();

5. cookie.remove()

If you might need to remove cookies, you can do it like this:

cookie.remove('key');

for one cookie, or like this:

cookie.remove('key1', 'key2');
cookie.remove(['key1', 'key2']);

for mutiple cookies.

6. cookie.enabled()

Sometimes saving cookies is disabled. You may check that like this:

if (cookie.enabled()) {
   // Do stuff with cookies
} else {
   // Display error message or use localStorage
}

7. Conslusion

It is very simple to use cookies like this. Give it a try!