JavaScript Cookies featured image

Introduction to Cookies: Understanding and Working with JavaScript Cookies

Browser cookies, or HTTP cookies, are text files made up of tiny bits of data. Websites use this information to track a user’s journey, allowing them to offer tailored-fit features and improve their browsing experience. Cookies can store up to 4096 bytes of data. However, we can add a limited number of cookies per domain, depending on the browser.

A basic understanding of HTTP cookies is essential for any internet user, whether you’re just browsing for fun or making a living from it. This guide will introduce you to cookies and their various types in detail. Our focus is to help you understand and work with JavaScript Cookies.

Let’s start!

Prerequisites

To follow along with this tutorial, you must have:

Getting Started with JavaScript Cookies

Working with JavaScript cookies is straightforward. It allows to create, edit, and retrieve cookies effortlessly. Besides, we can use the Document object’s cookie property to manipulate and restrict cookies properties like name, value, and length, to name a few.

Types of Cookies

First, let’s take a look at the different types of cookies:

  1. First-Party Cookies

These cookies are created and stored every time a user visits a website. It allows website owners to get detailed insight into users’ data and provide them with a better browsing experience.

  1. Persistent Cookies

For this kind of cookie, the issuer assigns an expiration date. Hence, it is used for a much longer period of time. This means that even if you close your browser, the cookie will remain on it. Also, the data is returned to the issuer each time you visit the website that created the cookie.

  1. Session Cookies

These cookies are only temporary and will be stored in your browser’s memory while it is open. When you close it, the cookie is removed from your browser’s history, making them a lower security risk. You do not need to specify an expiration date.

  1. Third-Party Cookies

Third-party cookies get created by a site you are not currently visiting. Mostly, these cookies are helpful in tracking a user who has clicked on an ad associating them with the domain that referred them.

Creating Cookies

We can create cookies using two methods:

  1. Send Set-Cookie in the HTTP response header. Depending on the technologies used for the web server, you can manage cookie headers using tools and libraries. Cookies can contain information such as an expiration date and security features like the secure directive and the HttpOnly flag.

  • HttpOnly: It indicates that the browser cannot read or modify cookies.

  • Secure: This indicates that the cookie can only be sent over HTTPS.

  1. Using the JavaScript document.cookie property, we can create, read, and delete cookies.

Step 1 — Creating a Cookie

Next, we will demonstrate the process of creating a JavaScript cookie. Cookies are saved in name-value pair format:

In the above cookie, UserName is the name of the cookie whereas CloudSigma is the value stored in it.

The cookie has an expiry date. By default, it gets deleted automatically upon shutting off the browser. You can also add an expiry date to your cookie:

By default, cookies belong to a current page. However, we can also specify the cookie with the help of the path parameter:

  • Cookie Max-Age vs Cookie Expire

Depending on your needs, you may use these two strategies to set a cookie’s expiry date. The difference between the two is expires sets an expiry date when a cookie gets deleted. On the contrary, the max-Age sets the time in seconds when a cookie will be deleted. Unfortunately, max-age is not supported by all browsers.

Example of setting a cookie using expires and max-age:

Expires:

Max-age :

Step 2 — Reading a Cookie

The document.cookie attribute returns a string. If there are two or more cookies, we use a semicolon( ;) and space to separate them.

We use the split() method to extract an individual cookie from a list of cookies. This method breaks down the list into individual names and value pairs. Once done, you can then search for the target cookie you want to read:

Let’s understand the functions we created in the code:

Function Name Description
setCookie() Creates a cookie
getCookie() Reads the value of the cookie
checkCookie() Verifies whether the UserName is set or not.

In the next step, we will learn how to update a cookie.

Step 3 — Updating a Cookie

We can set new values to our cookie attributes. In our example, let’s update the user’s subscription from monthly plan to quarterly plan.

Let’s update the max-age attribute of the UserName cookie from 30 days to 180 days:

Step 4 — Deleting a Cookie

Renaming the cookie with the same name will delete the cookie you want to erase. We can delete a cookie by setting the max-age attribute to 0:

Additionally, if the cookie has a specified path, delete it by specifying it:

Conclusion

Cookies are necessary for a website to work and function properly. In this introductory tutorial, we discussed cookies and their different types in detail. Additionally, we have learned to work with cookies with the help of an example. Now that you are comfortable using JavaScript cookies, start creating customized cookies to learn and explore more on the topic.

Furthermore, there are many tutorials on JavaScript, and web development that you can explore from our blog:

Happy Computing!