umma.dev

Cookies in JavaScript Applications

Here I give a brief overview of cookies. Discussing what the difference is between sessions, cookies and local storage.

What are Cookies?

Cookies store data related to the user on the browser. Cookies tend to communicate between the server and browser through header requests. Authentication is an example of a use case for cookies; each user will be given an authentication token whey they log in, the server accesses the cookie to authenticate the user and retrieve data about the user. When a browser requests a web page from a server, cookies belonging to the page are added to the request, and thus the website remembers the user when they return. Cookies will be set to have an expiry date.

Local Storage

Local storage within a web browser is used to read and write data. The data is stored in key-balue pairs. It’s important to note that here, the server can’t access your computer’s local storage.

Sessions

A session is used to save data on the server for a short period of time, so that it can be used on pages of a website. For example when a user logs in to a network, a session will start and the session ends when they log out.

Unlike cookies, a session can hold an indefinite quantity of data and store unlimited data.

Example of Cookies

Though for most modern web applications you would not use the code below, it shows the main functionality of cookies.

function setCookie(cname, cvalue, exdays) {
  const d = new Date();
  d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
  let expires = "expires="+d.toUTCString();
  document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}

function getCookie(cname) {
  let name = cname + "=";
  let ca = document.cookie.split(';');
  for(let i = 0; i < ca.length; i++) {
    let c = ca[i];
    while (c.charAt(0) == ' ') {
      c = c.substring(1);
    }
    if (c.indexOf(name) == 0) {
      return c.substring(name.length, c.length);
    }
  }
  return "";
}

function checkCookie() {
  let user = getCookie("username");
  if (user != "") {
    alert("Welcome again " + user);
  } else {
    user = prompt("Please enter your name:", "");
    if (user != "" && user != null) {
      setCookie("username", user, 365);
    }
  }
}