How to use JavaScript to create, read, update, and delete cookies

JavaScript: reading cookies in Chrome Developer Console

Cookies are a convenient mechanism for saving state (e.g. user login, user preferences, settings, etc.) across multiple pageviews across multiple sessions. Cookies can be manipulated both on server-side and client-side. For a full breakdown on the topic, check out this excellent primer on cookies on MDN.

This guide will show you how to manipulate cookies client-side using JavaScript.

 

document.cookie

While you’re on an HTML page, all cookies associated with that domain can be accessed via this JavaScript command:
document.cookie
Let’s see it in action:
  1. Visit your favourite site (e.g. reddit.com)
  2. Open up your browser’s developer console (in Chrome use the shortcut ⌘ + option + J)
  3. Type in document.cookie and press the return key
  4. You will now see all the cookies associated with this domainJavaScript: reading cookies in Chrome Developer Console

 

This is how you interpret the output of document.cookie :

  • You are looking at all cookies associated with the domain concatenated into a single string.
  • Each cookie is separated by the “;” character.
  • Each cookie is a key-value pair separated by the “=” character. The key is on the left of the = character, and the value is on the right.

document.cookie gives us our fundamental building block for managing cookies client-side. So how do we manipulate cookies? Read on!

A JavaScript library for managing cookies

I’ve put my code into a simple JavaScript library so I can reuse it in the future. Feel free to take a copy for your own purposes.

 

Setting cookies

You can create a new cookie by assigning a string to the document.cookie object. The string will contain the following:
  • Cookie name
  • Cookie value
  • Expiry date
  • Path or scope – in the below code the path is set to “/“ so that the cookie is accessible across all pages on the site. You could modify this to only apply to a specific directory or set of directories.

So to set a cookie, we invoke the below code.

cookieHandler.setCookie = function (cookieName, cookieValue, nDays) {
    var d = new Date();
    d.setTime(d.getTime() + (nDays*24*60*60*1000));
    var expires = "expires="+ d.toUTCString();
    document.cookie = cookieName + "=" + cookieValue +
        ";" + expires + ";path=/";
}

//Example: set a cookie that expires one year from now
cookieHandler.setCookie('my_cookie', '12345', 365);

 

Note that when you assign a value to document.cookie, you are not replacing the entire document.cookie object. Instead the JavaScript engine will do one of two things depending on if:
  • The cookie is new – the new cookie details will be appended to document.cookies
  • The cookie already exists – the cookie string will be replaced in document.cookies

 

Updating cookie values

Updating cookie values simply involves calling cookieHandler.setCookie() with the original cookie name and a new value. The existing cookie will have its value replaced with the new value.

//Example: update value of 'my_cookie' to 67890
cookieHandler.setCookie('my_cookie', '67890', 365);

 

Reading cookie values

To get the value of a cookie, we need to go through the following steps:
  • Read the string representation of document.cookie. Remember, this returns a representation of all cookies.
  • Split the string into its individual cookie components.
  • Iterate through the individual cookies. For each cookie string:
    • Split the cookie into its key-value pair.
    • If the key matches the name of the cookie you are looking for, then return the value.
  • If no cookies matches your search, return an empty string.

Thus to get the value of a cookie, we run the code below.

cookieHandler.getCookieValue = function (cookieName) {
    var name = cookieName + "=";
    var decodedCookie = decodeURIComponent(document.cookie);
    var ca = decodedCookie.split(';');
    for(var i = 0; i <ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }

    return '';
}

//Example: get value of the 'my_cookie' cookie
cookieHandler.getCookieValue('my_cookie');

 

Deleting cookies

The easiest way to delete a cookie is to set its value to an empty string and its expiry time to a time in the past. For added measure I set the expiry date to two years in the past.

cookieHandler.deleteCookie = function (cookieName) {
  cookieHandler.setCookie(cookieName,'',-730);
}

//Example: delete the 'my_cookie' cookie
cookieHandler.deleteCookieI('my_cookie');

 

Did you find this helpful and think it would be beneficial for someone else? Share now!

Leave a Reply

Your email address will not be published. Required fields are marked *