Tutorials Tonight's Logo

JAVASCRIPT COOKIE


Cookies let you store user's data in the browser for you. A cookie is the most commonly used method for remembering user.

In this JavaScript cookie article, you will learn about cookies in-depth.

What are Cookies?

Cookies in browsers are small strings of user data that is stored in browsers.

A cookie is a part of the HTTP protocol which let you store users data in a browser for a period of time.

In most commercial and non-commercial websites it is required to maintain among different pages. For example, login information across the different webpage of any website is maintained through cookie information.

A cookie is one of the most efficient ways of tracking and remembering actions, interests, purchases, preferences, etc.

Cookies were invented to solve the problem of how to remembering users's information:

  • when a visits any webpage then user's name can be stored in cookie
  • Next time when user visit the page then cookie remembers the name

Cookies stores the information in key-value pair. Example:

username=john smith


How do cookies work?

  • When a user request for something then the server detects it as a new user even when the user has already interacted with the server.
  • So to recognize the old user server respond with a cookie.
  • If the user accepts the cookie then the cookie is stored in the browser in form of plain text in a user's hard drive.
  • Next time when the user arrives at another page of the same website then the browser sends the same cookie to the server for retrieval for the server to remember about this user.
javascript cookie | how cookie works

Cookies are plain text data which store data in key-value pair. It consists of 5 variable-length fields:

  • Expire - The date at which cookie will expire. If this field is blank then by the cookie will expire when the user quit the browser.
  • Domain - It provides domain name (name) of the website.
  • Path - The path or webpage that sets the cookie.
  • Secure - This makes the cookie only accessible through a secure server. If the field contains the word "secure" then the cookie is only retrieved with a secure server while if this field is blank, there are no such restrictions.
  • name=value - Cookies store data in a key-value pair.



JavaScript provides document.cookie object which returns all the cookies associate with the document.

Let's check if your browser stores any cookie from this site.

let allCookies = document.cookie;
alert(allCookies); // return empty string if no cookie
▶ Try It

The document.cookie returns all the cookie in 1 string saperated by a semicolon and a space, like: cookie1:value1; cookie2:value2; cookie3:value3;


Using document.cookie you can not only read cookie but can also create, update and delete the cookie.

To create a cookie set cookie data in key-value pairs.

document.cookie = "user=john smith"; // creating cookie
alert(document.cookie); // read cookie
▶ Try It

You can also set the expiry date of the cookie. The expiry date should be in UTC time.

By default, the cookie is deleted when the user quit the browser.

The following example sets a cookie that expires in 24 hours.

let time = new Date(new Date() + 24 * 60 * 60 * 1000);
time = time.toUTCString();
document.cookie = "user=john smith; expire=" + time; // setting 24 hour expiry time
alert(document.cookie);
▶ Try It

You can set what path or location cookie belongs to. The url path must be absolute, it makes cookie accessible in the page under those path.

For example, if cookie set in path /home then the cookie is accessible in /home, /home/shop, etc but not in /category or /offers.

You should usually set a cookie to the root path=/. By default, cookie belongs to the current page.

document.cookie = "user=john smith; path=/"; // setting path as root
alert(document.cookie);
▶ Try It

A domain defines from where the domain is accessible. The default value is the site itself.

A cookie set at one site is practically not accessible at another site even if you set domain value to that site, also it is not accessible at its subdomain.

However, if you explicitly set the domain of the cookie then only it is accessible at sub-domain.

// never accessible at site2.com when set at site.com
document.cookie = "user=john smith; domain=/site2.com";
// only accessible at site.com and not at shop.site.com
document.cookie = "user=john smith;";
// accessible at all sub domain like shop.site.com
document.cookie = "user=jack johnson; domain=site.com";
▶ Try It

When mentioned the word "secure" then the cookie is only accessible at the secure server.

By default, if you set a cookie at http://site.com then you can access it from https://site.com and vice versa. but if "secure" is set in the cookie and cookie is set by HTTPS protocol then it is not accessible through HTTP protocol.

document.cookie = "user=john smith; secure;";
alert(document.cookie);
▶ Try It


You can change the cookie the same way you created it.

Update the value of cookie using document.cookie.

// OLDER - "user=john smith;"
document.cookie = "user=Bob johnson; expires=Mon, 12 Jan 2050 12:00:00 UTC; secure;"; // updating
alert(document.cookie);
▶ Try It

To delete a cookie just set the expiration date with a passed date, which makes cookie expired and gets deleted.

You must specify the cookie path to ensure right cookie deletion.

document.cookie = "user=john smith; expires=Mon, 12 Jan 2000 12:00:00 UTC; path=/"; // updating
alert(document.cookie);
▶ Try It

Here is an example below which creates a cookie by taking the user's name in the input.

If user already visited the page and filled the name then it alerts a message and welcomes the user.

There are 2 functions in the example below:

  1. A function to check the cookie
  2. A function to set the cookie

A function to set the cookie

If the cookie does not exist then we will set a cookie with an expiration time of 24 hours.

The function accepts cookie name, cookie value and expiration time in days.

function setCookie() {
  let cookieName = prompt("Enter cookie name:");
  let cookieValue = prompt("Enter cookie value:");
  let expireDay = prompt("Enter expiry days:");
  let now = new Date();
  let expireTime = new Date(now + expireDay * 24 * 60 * 60 * 1000);
  document.cookie = cookieName + "=" + cookieValue + "; " + "expire=" + expireTime.toUTCString() + "path=/";
}

A function to check the cookie

When a user visits the page then we will first check if the cookie exists or not.

If the cookie does not exist then we will use prompt to take user name as input.

function checkCookie(cookieName) {
  let allCookies = decodeURIComponent(document.cookie);
  cookieArray = allCookies.split(';');
  for (var i = 0; i < cookieArray.length; i++) {
    name = cookieArray[i].split('=')[0];
    value = cookieArray[i].split('=')[1];
    if (name == cookieName) {
      alert("Welcome " + value);
      return;
    }
  }
  setCookie();
}

Here is complete working code:

function checkCookie(cookieName) {
  let allCookies = decodeURIComponent(document.cookie);
  cookieArray = allCookies.split(';');
  for (var i = 0; i < cookieArray.length; i++) {
    name = cookieArray[i].split('=')[0];
    value = cookieArray[i].split('=')[1];
    if (name == cookieName) {
      alert("Welcome " + value);
      return;
    }
  }
  setCookie();
}
function setCookie() {
  let cookieName = prompt("Enter cookie name:");
  let cookieValue = prompt("Enter cookie value:");
  let expireDay = prompt("Enter expiry days:");
  let now = new Date();
  let expireTime = new Date(now + expireDay * 24 * 60 * 60 * 1000);
  document.cookie = cookieName + "=" + cookieValue + "; " + "expire=" + expireTime.toUTCString() + "path=/";
}
checkCookie("user");
▶ Try It


Follow Us

Copyright © Tutorials Tonight. All Rights Are Reserved.