Bit Hacker Logo
Bit Hacker Logo
JavaScript Cookies

JavaScript Cookies

Despite being one of the most delicious snacks on the planet, Cookies are also small pieces of data used by browsers to store information. They site on your computer and your browser will use the to exchange information with a website. Most commonly, they are used to track user details such as login status, or preferences and even the dreadful ads proliferating the internet.

At some point, every JavaScript developer will need to interact with Cookies and this article will show you what standard browser methods are available in JavaScript and some re-usable code to make your life easier.

Anatomy of a Browser Cookie

A cookie itself is a simple string of information that stores data as a key/value pair. When you interact with cookies in JavaScript they are automatically tied to the domain name you are associated with. Below is an example of a cookie:

userid=2; expires=Fri, 27 Aug 2021 10:00:00 UTC; path=/

The first section is the key/value pair userid=2 seperated with a ; followed by the expiry of the cookie and the path. The path itself is optional and allows you to restrict the cookie to a path within the website to avoid collisions with other paths. For example, having two different applicationse domain.com/app1 and domain.com/app2 with out a path would share the cookies.

Read a cookie

It really is more like reading the cookies. JavaScript does not allow you get individual cookies but allows you to read all available for the page. This is done with:

var cookies = document.cookie;
> userid=2; anothercookie=3

You may wonder what happened to the expiry, and path. These values are not returned when you read the actual cookies. The return format will always be just the key/value pair cookie=value;cookie2=value.

Set cookies

document.cookie is used when assigning new cookies. While retrieving cookies returns all cookies through document.cookie you will set cookies individually one by one. Weird, I know, but older technology has its charm.

document.cookie = "userid=2; expires=Fri, 27 Aug 2021 10:00:00 UTC; path=/"
document.cookie = "anothercookie=3; expires=Fri, 27 Aug 2021 10:00:00 UTC; path=/"

Delete a cookie

To delete a cookie we interact with document.cookie again but use the expires field to wipe it out. This is done by selecting a past date for expiry and setting the value to nothing.
by one. Weird, I know, but older technology has its charm.

document.cookie = "userid=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/"

That's not fun

While we have a way of interacting with cookies, it is not at all elegant. We can do better. I always use a set of functions to make my life a bit easier when interacting with cookies. Lets write a few functions to read, set and delete cookies.

readCookie()

The theory is straight forward. Our cookies are always in key/value pairs with semicolons as separators. So in our read method we will split the cookie string and search through the array for our cookie. After splitting, our values will look like name=John so we can use split again to separate the key from the value.

We will also use a built in browser function decodeURIComponent before splitting to convert specially encoded characters such as %3F to ?. This practice is common when dealing with data going to and from a server via web requests.

Finally we return undefined if we did not find the cookie. We could return false, but that might indicate we found a cookie with the value of false. Using undefined is more of an indication that it was not set.

function readCookie(name) {
    var decCookies = decodeURIComponent(document.cookie);
    var cookies = decCookies.split(';');
    for( var i=0; i<cookies.length;i++){
        var cookie = cookies[i].split("=");
        var key = cookie[0];
        if( key == name ) {
            return cookie[1];
        }
    }
    return undefined;
}

setCookie()

Setting our cookie is even more straight forward. Pass in the value and the expiry date and assign it to document.cookie.

function setCookie(name,value,expires) {
    document.cookie = name + "=" + value + "; expires=" + expires.toUTCString();
}
setCookie("name","John",new Date(2022,1,1,10,0,0));
> "John"

removeCookie()

Ok, removing is even more straight forward. You do not even need a separate function for this, as you can just set a past expires date with the set() function. But for coding sake!

function removeCookie(name) {
    setCookie(name,"",new Date(1970,1,1,0,0,0));
}
setCookie("name","John",new Date(2022,1,1,10,0,0));
removeCookie("name");
> undefined

Decorating your Cookies

Putting it together into a nicely accessible Cookie object will keep things nice and clean. We can shorten up the function names as they will be redundant.

const Cookie = {
    read(name) {
        var decCookies = decodeURIComponent(document.cookie);
        var cookies = decCookies.split(';');
        for( var i=0; i<cookies.length;i++){
            var cookie = cookies[i].split("=");
            var key = cookie[0];
            if( key == name ) {
                return cookie[1];
            }
        }
        return undefined;
    },
    set(name,value,expires) {
        document.cookie = name + "=" + value + "; expires=" + expires.toUTCString();
    },
    remove(name,value,expires) {
        Cookie.set(name,"",new Date(1970,1,1,0,0,0));
    }
}

There you have it! Go forth and enjoy your cookies.