Vanilla JavaScript Cookies 🍪

Today we'll be looking into working with Cookies in JavaScript. It's not the most widely used function, but great to keep track of small things like whether someone clicked a cookie bar.

We can set, get, change and, delete a cookie.

To set a cookie in JavaScript, we use the document.cookie property.

First we must understand cookies are set as a key, value pair

key = value

So to set a cookie:

document.cookie = 'username=Chris';

We can even set a expire date:

document.cookie = 'username=Chris; expires=Sun, 01 Jan 2023 12:00:00 UTC';

To read a cookie we can use the following:

var username = document.cookie;
username = Chris;
second = bla;

This will return the full cookie object, so we need to split it ourself like so:

var username = getCookie('username');
console.log(username);
// Chris

function getCookie(name) {
  // Add the = sign
  name = name + '=';

  // Get the decoded cookie
  var decodedCookie = decodeURIComponent(document.cookie);

  // Get all cookies, split on ; sign
  var cookies = decodedCookie.split(';');

  // Loop over the cookies
  for (var i = 0; i < cookies.length; i++) {
    // Define the single cookie, and remove whitespace
    var cookie = cookies[i].trim();

    // If this cookie has the name of what we are searching
    if (cookie.indexOf(name) == 0) {
      // Return everything after the cookies name
      return cookie.substring(name.length, cookie.length);
    }
  }
}

Sometimes we want to update a cookie; this is the same as the creation:

document.cookie = 'username=Nicole; expires=Sun, 01 Jan 2023 12:00:00 UTC';

To delete a specific cookie, we have to set its date to be passed:

document.cookie = 'username=; expires=Thu, 01 Jan 1970 00:00:00 UTC;';

View the demo to test with on Codepen.

View on Codepen.

Thank you for reading, and let's connect!

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter

No Comments Yet