Course: JavaScript

Progress (0%)

JavaScript Cookies

Chapter 79 10 mins

Learning outcomes:

  1. What are cookies
  2. Creating and updating cookies
  3. Configuring cookies
  4. Deleting cookies

What are cookies?

If you've ever come across a pop-up while surfing a website asking you to accept cookies, and didn't quite understand what it really meant then this might be your question - what exactly are cookies? Can I eat them? We'll start by answering the latter - No, you can't eat HTTP cookies!!

And now onto the first one.

Cookies are basically data a webpage saves on a user's computer to remember him/her on the next visit.

The data here, is specifically a text file on the user's computer handled by the browser which requested the webpage.

Each browser has its own mechanism for storing cookies and hence a cookie created on one browser isn't accessible on another.

How cookies work?

Imagine for a second that you visit a webpage via Google Chrome. The browser sends a request to the site's server which along with the HTML for the page responds with some HTTP Headers. Amongst those headers it sends one to create a cookie with the namevisited and valuetrue.

Seeing this Chrome, creates a cookie file for this specific page on your computer. Although the cookie can be created for the entire domain, to keep things simple we'll just stick with a single page.

You surf the site for a while before closing it.

Now after sometime you again open the same page on Chrome - which realises a cookie is associated with it and thus sends the cookie data along with the request.

The server at the back end receives the cookie visited=true and realises that you have visited the given page before and can alter the content to match for the second visit.

This is cookies in action!

The whole cookie game is essentially played on the back end, however JavaScript enables us to play it on the front end too. And that is what we will be looking in this chapter - how to do cookie related stuff in JavaScript using the document.cookie property.

Creating a cookie

On a basic level, to create a cookie we need two things: a name and a value.

Following we create a cookie visited with value true in JavaScript using document.cookie.

document.cookie = "visited=true";

The name is followed by an equal-to = sign which is followed by the value.

And now if you log the property in the console you'll get something similar to this:

console.log(document.cookie); // "visited=true"

Creating multiple cookies

To create multiple cookies in JavaScript we can use the document.cookie property multiple times.

document.cookie = "visited=true"; // cookie 1
document.cookie = "timeSpent=50"; // cookie 2

Now if you were thinking that in line 2 we should've used the += operator instead of = here is the explanation for that.

document.cookie isn't a normal object property which can be overridden with another assignment statement. It is an accessor property - the previous value is stored when you are writing something to it.

Changing cookie values

If we want to change the value of visited from true to yes we will have to rewrite the whole statement with the new value as illustrated below.

document.cookie = "visited=yes";

Configuring cookies

Apart from a name and a value, a cookie can also take certain configurating directives defining things such as its expiry time, its path etc.

Following is a list of these configuration directives. They need to be preceded by a semi-colon ; after the value of the cookie.

In the list below where the text is in italic it is a value to be changed by the one you want.
  1. expires=date: sets the date in UTC format, on which the cookie will expire i.e be deleted. If not specified, the cookie will expire when the session ends i.e when the user closes the browser.
  2. max-age=time: specifies the time in seconds after which the cookie should expire, starting from the time its created.
  3. path=urlPath: sets the absolute path where the cookie is accessible. The values can be / (default) - accessible throughout the domain; /courses - accessible in the courses directory and so on. Having a path like ../ won't work since it is a relative path.
  4. secure: indicating the cookie to be transmitted over https only.
  5. samesite=strict: ensures that the cookie isn't sent to other sites via cross-site requests i.e when someone else embeds your site in an iframe.

Let's put some of these into real examples.

Following we have a cookie that expires 1 hour after the current date:

var date = new Date();
date.setMinutes(date.getMinutes() + 60);
document.cookie("visited=true;expires=" + date.toUTCString());
Converting the date here to UTC Format is important. If not done, the cookie might not expire as expected!

Following we have a cookie that is accessible in the /courses directory and expires 1 hour after the current date:

var date = new Date();
date.setMinutes(date.getMinutes() + 60);
document.cookie("visited=true;path=/courses;expires=" + date.toUTCString());

Following we have a cookie which will be sent only over https.


Getting cookie values

Getting cookie values in JavaScript isn't quite straight-forward as you might think. There is no native function available that can take a cookie's name as an argument and return its value, if is exists or false, if it doesn't.

Therefore we have to deal with this problem ourselves. But its good in a way: we get to learn how to solve problems using the concepts we've learnt so far.

Coming back to the problem, we can solve it in two ways: the first one is shown below whereas the second one is regular expressions.

Follow along each statement in the code below:

var name = "visited"; // the cookie to find value of
var value = "";
var cookiesArr = document.cookie.split("; "); // split the string on ;

for (var i = 0, len = cookiesArr.length;i < len;i++) {
   // check if the name-value pair contains "visited"
   if (cookiesArr[i].indexOf("visited") !== -1) {
      cookie = cookiesArr[i]; // the current name-value pair
      // slice the string by removing the name and =
      value = cookie.slice(name.length + 1, cookie.length);

If you are really good in JavaScript then you wouldn't have a hard time understanding what this code is doing. Furthermore there is even a slight problem with this code - there is one case where the output might be wrong.

Let's see whether you can figure it out.

Deleting cookies

To delete a cookie we can either set its expiry date in the past using expires, or its max-age equal to 0. And to do this we would again have to re-define the whole statement.

Following we delete the cookie visited using a past date and converting it to UTC Format.

var pastDate = new Date(0).toUTCString(); 
document.cookie("visited=true;expires=" + pastDate);
Converting the date here to UTC Format is important. If not done, the cookie might not expire as expected!

And following we do the same thing of deleting the cookie, but now with max-age:

document.cookie("visited=true;max-age=" + 0);
// delete the cookie after 0 seconds have passed

"I created Codeguage to save you from falling into the same learning conundrums that I fell into."

— Bilal Adnan, Founder of Codeguage