Using cookies in JavaScript

In this article we'll learn how to save cookies, update cookies, and delete cookies in JS

By: Ajdin Imsirovic 26 January 2021

Cookies are one of the oldest ways of saving text-based data on the web. The data that gets saved is not meant to be large. It’s use case is to “remember” some things about the user, even after they have closed the web page or the browser. In this article, we’ll learn about working with cookies in JS.

Cookies

Actually, cookies as a means of storing information are older then even localStorage. They both serve a similar role (of storing data).

Cookies, however, come with a special feature: the expiration date/time. Once a cookie is past the specified date/time, the browser simply deletes it. This also makes it possible to easily invalidate cookies, by setting their expiration to a time in the past, which immediately deletes them.

Cookies are meant to work with sessions, which have to do with data on a server.

Here’s how that is supposed to work:

  1. A browser sends a POST request to the server, containing a username and password before logging in to the website
  2. The browser receives and validates this data. If everything checks out, it adds a new session to the database, then sends a response to the browser, with the session id stored in a cookie.
  3. Next, the browser sends a request to the server, and in that request, sends the cookie received in step 2
  4. Since the browser receives the cookie, it can check the session id that comes with the cookie, and based on that session id, finds that specific user’s data and sends it back to the browser

One important thing to keep in mind is that cookies are both readable and writable. Additionally, it is our JS code that can both read and write, unless a restriction exists on the server to prevent this.

Working with cookies in vanilla JS can be a bit complex, but we’ll still go through the process to show how it works.

A cookie is set as a property on the document object:

document.cookie = "username=John";

We can set it with or without the expiry date:

document.cookie = "user=John; expires=Thu, 14 Jan 2021 12:00:00 UTC";

Once the expires datetime is here, the cookie’s data is deleted.

If we add another cookie with document.cookie, we will not override the previous one:

// sets the cookie last_name (user is NOT overwritten)
document.cookie = 'last_name=Doe; expires=Thu, 14 Jan 2021 00:00:00 UTC; path=/'

The path parameter in the above cookie is something we haven’t used before. This parameter describes what part of the site the cookie is for. The default value is the current page.

Here’s an example of deleting a cookie by setting its expiry in the past:

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

To retrieve cookies, we can simply do this:

let cookies = document.cookie;

This means that for any website we’re on, to inspect the cookies that are stored there, we simply run the above single line of code, and then we can inspect all the cookies like this:

cookies; // returns the full cookies string

As written in the comment above, this will retrieve all the cookies, in the form of a string. This string can be quite long if there are more than a few cookies stored.

Here’s a function that we can use to retrieve a specific cookie (which we can pass in as a string argument to the function):

1
2
3
4
5
function getCookie(name) {
    let value = "; " + document.cookie;
    let parts = value.split("; " + name + "=");
    if (parts.length == 2) return parts.pop().split(";").shift();
}

Before we finish this exercise, there’s one important rule to remember: Never store a user’s login data, login name, password, and other important data in a cookie! This is a security hazard, because cookies are possibly accessible to almost anybody.

So, what can be stored in a cookie? A short answer is: a session ID.

We can store a session ID in a cookie, and then we store on the server, in a database, all the user’s sensitive information, under the session ID index.



Note:
This exercise comes from Book 3 of my book series on JS, available on Leanpub.com.



Feel free to check out my work here: