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:
-
A basic understanding of JavaScript.
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:
-
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.
-
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.
-
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.
-
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:
-
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.
-
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:
1 |
document.cookie = "UserName = CloudSigma"; |
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:
1 2 3 |
document.cookie = "UserName = CloudSigma"; expires=Fri, 11 Jun 2022 12:00:00 UTC"; document.cookie = "UserName = CloudSigma"; |
By default, cookies belong to a current page. However, we can also specify the cookie with the help of the path parameter:
1 2 |
document.cookie = "UserName = CloudSigma"; expires=Fri, 11 Jun 2022 12:00:00 UTC; path=/"; |
-
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:
1 2 3 |
var d = new Date(); d.setTime(d.getTime() + 5*60*1000); // in milliseconds document.cookie = 'foo=bar;path=/;expires='+d.toGMTString()+';'; |
Max-age :
1 |
document.cookie = 'foo=bar;path=/;max-age='+5*60+';'; |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
function setCookie(name, count, validityCheck) { var cookie = name + "=" + encodeURIComponent(value); if(typeof validityCheck === "number") { cookie += "; max-age=" + (validityCheck*24*60*60); document.cookie = cookie; } } function getCookie(name) { var cookieArr = document.cookie.split(";"); for(var i = 0; i < cookieArr.length; i++) { var cookiePair = cookieArr[i].split("="); if(name == cookiePair[0].trim()) { return decodeURIComponent(cookiePair[1]); } } return null; } function checkCookie() { var UserName = getCookie("UserName"); if(UserName != "") { alert("Welcome again, " + UserName); } else { firstName = prompt("Enter your UserName:"); if(UserName != "" && UserName != null) { setCookie("UserName", UserName, 30); } } } |
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:
1 2 |
document.cookie = "UserName=CloudSigma; path=/; max-age=" + 30 * 24 * 60 * 60; document.cookie = "UserName=CloudSigma; path=/; max-age=" + 90 * 24 * 60 * 60; |
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:
1 |
document.cookie = "UserName=; max-age=0"; |
Additionally, if the cookie has a specified path, delete it by specifying it:
1 |
document.cookie = "Username = ExcellentDesign; Path = /"; |
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:
- Basics of JavaScript: How to Work with Date and Time
- JavaScript: A Tutorial on How to Index, Split and Manipulate Strings
- A Tutorial on Working with JSON in JavaScript
Happy Computing!
- How To Enable, Create and Use the .htaccess File: A Tutorial - March 8, 2023
- An Overview of Queries in MySQL - October 28, 2022
- Introduction to Cookies: Understanding and Working with JavaScript Cookies - October 25, 2022
- An Overview of Data Types in Ruby - October 24, 2022
- The Architecture of Iptables and Netfilter - October 10, 2022