JavaScript

How to set, check and read a cookie value with JavaScript?

Cookies are small text files that keep a small bit of data on the user’s computer (around 4KB) and are used to store information about a user, for example, a user’s preferences for a website which the website can retrieve to personalize the web page when the user visits the site again. To put it simply, cookies help in a more convenient and personal website visit for the users. A cookie is sent to your computer by a website when you visit it and is saved in a file on your computer that’s accessible through your web browser.

We will talk about how to set, check and read a cookie value with JavaScript in this article. However, before going any further let me stress on the point that cookies should not be used for storing critical/sensitive information like passwords or details of your credit card since malicious individuals could access them.

Creating a Cookie

The document.cookie property creates, reads, and deletes cookies and this is the property, which represents all of the cookies connected with a document. To create a cookie first we should know that cookies are saved in name-value pairs for example:

username = Obama;

Let us now create a cookie in JavaScript:

document.cookie = "username=Obama";

A cookie’s lifetime is set to the duration of the current browser session, which means it expires when the user closes the browser. To solve this problem we use the max-age attribute which ensures that the cookie persists beyond the current browser session. In the max-age attribute, we can specify the lifetime of a cookie in seconds i-e how long will the cookie remain before it is deleted. The life span of the cookie in the below code is 30 days:

document.cookie = "username=Obama; max-age=" + 30*24*60*60;

We can also use the expire attribute which takes the exact date rather than seconds in the GMT/UTC format and on that date the cookie expires:

document.cookie = "username=Obama; expires=Thu, 26 Sept 2021 12:00:00 UTC";

Another attribute we can use in the creation of Cookie is the path attribute which tells the browser what path the cookie belongs to rather than the default path which is the current page.

document.cookie = "username=Obama; expires=Thu, 26 Sept 2021 12:00:00 UTC; path=/";

We have to use the Javascript encodeURIComponent() as the cookie value contains commas, semicolons, and spaces and the encodeURIComponenet() ensures that the string doesn’t contain the commas, semicolons, and spaces as these are not allowed in cookies.

document.cookie = "Username=" + encodeURIComponent("Obama");

Reading cookie

We can read or get all the cookies of a current domain by using the document.cookie:

var x=document.cookie;

Just like in creating a cookie we used encodeURIComponent() in reading a cookie we have to use decodeURIComponenet() :

document.cookie = "Username=" + decodeURIComponent("Obama");

Deleting Cookie

We can also delete a cookie and in JavaScript, the process is very simple as we don’t have to specify some cookie value rather we can use the expire parameter and update it by using a past date for example:

document.cookie = "username=Obama; expires=Thu,20 Nov 2018 12:00:00 UTC; path=/";

Deleting Cookie

We can also delete a cookie and in JavaScript, the process is very simple as we don’t have to specify some cookie value rather we can use the expire parameter and update it by using a past date for example:

document.cookie = "username=Obama; expires=Thu,20 Nov 2018 12:00:00 UTC; path=/";

Cookie Example In JavaScript

Now that we know what a cookie is, how to create or read a cookie, let’s combine all that we have learned and create a cookie that stores a name whenever a user visits our website. We will take an input name from the user when the user enters our website for the first time and will store it in a cookie. When the user enters the website again he/she will get a welcome message on the website.

To implement the above example, we will need 3 functions in which one of the functions will set a cookie, one will read/get a cookie value and the last function will check the cookie value.

Set Cookie Function

function setCookie(username, value, expiry) {
  const date = new Date();
  date.setTime(date.getTime() + (expiry * 24 * 60 * 60 * 1000));
  var expires = "expires="+date.toUTCString();
  document.cookie = username + "=" + value + ";" + expires + ";path=/";
}

Get Cookie Function

function getCookie(username) {
  let name = username + "=";
  let spli = document.cookie.split(';');
  for(var j = 0; j < spli.length; j++) {
    let char = spli[j];
    while (char.charAt(0) == ' ') {
      char = char.substring(1);
    }
    if (char.indexOf(name) == 0) {
      return char.substring(name.length, char.length);
    }
  }
  return "";
}

To obtain a single cookie we used the split method which will break down the name=value pairs and then search for the name we want.

Check Cookie Function

function checkCookie() {
  var user = getCookie("username");
  // checking whether user is null or not
  if (user != "") {
    //if user is not null then alert
    alert("Welcome again " + user);
  }
  //if user is null
  else {
    //take input from user
    user = prompt("Please enter your name:", "");
    //set cookie
    if (user != "" && user != null) {
      setCookie("username", user, 365);
    }
  }
}

checkCookie();

The check cookie simply checks whether the name exists or not i-e whether the user has first visited our site or not. It checks by first calling the getCookie() method which checks whether the username exists or not and then if it exists displays the welcome message with the name of the user. If the username doesn’t exist then it calls the setCookie() method and the user then enters the name and the cookie is set.

Below are the screenshots of when I first visited the site:

Below is the screenshot showing the name I set after refreshing the page:

Conclusion

A cookie is a small text file consisting of some information about a user and is a data packet that a computer receives and then sends back without altering or changing it. The browser cookies help in keeping track of user visits and user activities. For example, you have added some items to your cart and you are exploring the site and went to another page or you accidentally refresh it, without cookies your cart would become empty. We looked at how to set, check, and read cookies in JavaScript with examples in this post.

About the author

Shehroz Azam

A Javascript Developer & Linux enthusiast with 4 years of industrial experience and proven know-how to combine creative and usability viewpoints resulting in world-class web applications. I have experience working with Vue, React & Node.js & currently working on article writing and video creation.