JavaScript Cookies


Cookies allow you to save details about users on web pages.


What are Cookies?

Cookies are bits of information kept in tiny text files on your computer.

Once a web server sends a webpage to a browser, the connection ends, and the server doesn't remember anything about the user anymore.

Cookies were created to solve the issue of "how to recall information about the user".

  • When someone goes to a webpage, their name might be saved in a cookie.
  • The next time someone comes back to the page, a cookie will keep their name saved.

Cookies store information in pairs, like this:

username = John Doe

When you ask for a web page from a server using your browser, the cookies from that page are sent along with your request. This helps the server to have the important information it needs to keep track of users' details.

If your browser doesn't allow local cookies, none of the examples below will function properly.


Create a Cookie with JavaScript

JavaScript has the ability to make, check, and remove cookies using the document.cookie feature.

Using JavaScript, you can make a cookie in the following way:

document.cookie = "username=John Doe";

You can set a time for cookies to expire (in UTC time). Normally, the cookie gets removed once you close the browser.

document.cookie = "username=John Doe; expires=Thu, 18 Dec 2013 12:00:00 UTC";

Using a path parameter helps inform the browser about the specific path associated with a cookie. By default, the cookie is linked to the current page.

document.cookie = "username=John Doe; expires=Thu, 18 Dec 2013 12:00:00 UTC; path=/";

Read a Cookie with JavaScript

To use JavaScript to read cookies, follow this code:

let x = document.cookie;

The code document.cookie shows all cookies together in a single string, like this: cookie1=value; cookie2=value; cookie3=value;


Change a Cookie with JavaScript

Using JavaScript, you have the ability to modify a cookie just as you initially set it up.

document.cookie = "username=John Smith; expires=Thu, 18 Dec 2013 12:00:00 UTC; path=/";

The original cookie has been replaced.


Delete a Cookie with JavaScript

Removing a cookie is easy.

When you delete a cookie, you don't need to mention what the cookie's value is.

Simply adjust the 'expires' parameter to a date in the past:

document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";

Make sure to set the cookie path correctly so you can delete the intended cookie.

Certain web browsers may prevent you from removing a cookie unless you specify its path.


The Cookie String

The document.cookie property may seem like a regular text string, but it's not.

When you write a complete cookie string to document.cookie, only the name-value pair is visible when you read it again.

When you create a new cookie, it doesn't replace the old ones. Instead, the new cookie gets added to the list of cookies in document.cookie. So, if you check document.cookie again, you'll see something like this:

cookie1 = value; cookie2 = value;

     

To find out the value of a particular cookie, you need to create a JavaScript function. This function will scan through the cookie string to locate the value of the desired cookie.


JavaScript Cookie Example

In the upcoming example, we'll make a cookie to save the name of someone who visits the website.

When someone comes to the webpage for the first time, they'll get a prompt to type their name. After typing their name, it's saved in a cookie.

When the visitor comes back to the page again, they will receive a welcome message.

We will make three JavaScript functions for this example.

  1. A function to put a value in a cookie
  2. A code to retrieve a cookie's value
  3. Code to Verify Cookie Value

A Function to Set a Cookie

Initially, we make a function that saves the visitor's name in a cookie variable.

Example

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=/";
}

Example explained:

The function mentioned here takes in three pieces of information: the name of the cookie (cname), what value the cookie should have (cvalue), and how many days until the cookie expires (exdays).

The code creates a cookie by combining the name of the cookie, its value, and the expiration time.


A Function to Get a Cookie

Next, we make a function that gives back the value of a chosen cookie.

Example

function getCookie(cname) {
  let name = cname + "=";
  let decodedCookie = decodeURIComponent(document.cookie);
  let ca = decodedCookie.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 explained:

Please specify the cookie name as the parameter (cname).

Make a new variable called "name" and set it to the text you want to find, which includes "cname + "="."

Decode the cookie string to deal with cookies that have special characters like '$'.

Iterate through the 'ca' array using a loop (i = 0; i < ca.length; i++), and retrieve each value (c = ca[i]).

If the cookie is discovered (when it starts with the name), give back the value of the cookie (from the length of the name till the end of the cookie).

If the cookie isn't there, just give back an empty result.


A Function to Check a Cookie

Finally, we make a function to verify whether a cookie has been set.

If the cookie exists, it shows a greeting.

If the cookie isn't set, a message box pops up to ask the user's name. Then, it saves the username cookie for a year (365 days) using the setCookie function.

Example

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

All Together Now

The provided code executes the "checkCookie()" function when the webpage is opened.