How to Manage Cookies in JavaScript

John John (304)
5 minutes

At some point you'll want to read, set, and remove cookies using JavaScript. This is actually way more complicated than it should be so I'll provide a few example functions and refer you to a solid jQuery plugin.

Posted in these interests:
h/javascript27 guides
h/code69 guides

First you should understand what the cookie is and how it's set. A cookie is a string that is stored on the user's computer to allow data to persist throughout the user's session. Cookies are often set by HTTP response headers, but they can also be set directly in the browser using JavaScript. To read the entire cookie string you can access document.cookie.

What you'll likely see is a long string of semi-colon delineated key/value pairs.

You can manually set a cookie by setting document.cookie equal to the desired cookie using this format:

document.cookie = "name=tyler;expires=Thu, 03 Sep 2015 05:33:44 GMT";
This can be a little cumbersome, so the function below should make things easier.
function setCookie(name, value, exdays) {
    var d, expires;
    exdays = exdays || 1;
    d = new Date();
    d.setTime(d.getTime() + (exdays2460601000));
    expires = "expires=" + d.toUTCString();
    document.cookie = name + "=" + value + "; " + expires;
To set a cookie that lasts for one year, you could use:
setCookie('name', 'Batman', 365);

To read a cookie you can simply access document.cookie.

If you're searching for a specific value you can use the following function.
function getCookie(name) {
    var cookie, c;
    cookies = document.cookie.split(';');
    for (var i=0; i < cookies.length; i++) {
        c = cookies[i].split('=');
        if (c[0] == name) {
            return c[1];
    return "";
This function uses JavaScript's string split method to split the cookie string by semi-colons. Then it loops through the result array of strings and splits them again by "=" producing the cookie key/value pair. Then it simply tests the cookie key (c[0]) against the name of the cookie you are trying to read. If it matches it returns the value (c[1]).

To delete a cookie, you simply need to expire it. So deleting a cookie is basically setting the cookie with an expiration in the past. Using our setCookie function:

setCookie('name', '', -1);

If you're using jQuery, you might as well use this cookie plugin. It allows easy management of cookies.

// read
$.cookie('name'); // => "Batman"
// set
$.cookie('name', 'Iron Man');
// delete

It’s time for a project kit you can keep around the house.
Ash Ash (362)

The Raspberry Pi is a wonderfully flexible SBC and easily one of our favorite open-source boards on the market today.