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.

    Table Of Contents

  1. What are cookies?
  2. how does cookies work
  3. Different options in cookie
  4. Get cookie
  5. Set cookie
    1. Set cookie expire time
    2. Set cookie path
    3. Set cookie domain
    4. Set cookie secure
  6. Update cookie
  7. Delete cookie
  8. Get and set cookie function

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:

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

username=john smith


How do cookies work?

javascript cookie | how cookie works
JavaScript Cookie

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


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;
console.log(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
console.log(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
console.log(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
console.log(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;";
console.log(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
console.log(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
console.log(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) {
      console.log("Welcome " + value);
      return;
    }
  }
  setCookie();
}

Here is complete working code:

function checkCookie(cookieName) {
  let allCookies = decodeURIComponent(document.cookie);
  cookieArray = allCookies.split(';');
  cookieArray.forEach(cookie => {
    cookie = cookie.trim();
    console.log(cookie);
    let name = cookie.split('=')[0];
    let value = cookie.split('=')[1];
    if (name == cookieName) {
      console.log(name, value);
      return;
    }
  });
  // if cookie not found
  // 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 + ";expires=" + expireTime.toUTCString();
}
checkCookie("user");
Try It