Cookies in Javascript

Ranjul Arumadi
Last Updated: May 13, 2022

Introduction

Cookies in Javascript lets us store information on the user's computers. The amount of data stored is very small, nearly 4KB or so. The purpose of using cookies in Javascript is simple; they store information regarding the user's preferences in a website so that the next time the user visits the website, the website can be made to suit those needs. 

 

In this blog, let us see how to create cookies in Javascript, read, update, and delete them.

How do cookies work?

The way cookies work is that when a user sends a request to the server, then each of those requests is treated as a new request being sent by a different user. To recognize the old user, we need to add the cookie with the response from the server.

 

Now, whenever a user sends a request to the server, the cookie is added with that request automatically. With the help of these cookies, the server is able to recognize the users.

Working

Source: Canva

 

Some attributes related to cookies

AttributesDescription
max-agemax-age to be used to maintain the state of a cookie up to the specified time. Note that the time is given in seconds.
domainThe domain attribute is used to specify the domain for which the cookie is valid.
pathThe path attribute expands the scope of the cookie to all the pages of a given website.
samesite samesite is a security attribute.  It is used to protect from XSRF (cross-site request forgery) attacks.
encodeURIComponent()The encodeURIComponent() function is used to encode a URI(Uniform Resource Identifier) by replacing each instance of certain characters with one, two, three, or four escape sequences.
decodeURIComponent()The decodeURIComponent() function decodes a URI component previously created by encodeURIComponent().

Creating cookies in Javascript

Cookies are saved in name-value pairs. To create a cookie, we can use the document.cookie property. Let us see the code for doing that.

 

Code:

// Name-value pair used to store cookie information
document.cookie = "username=Ninja";

 

We can also set when the cookie has to expire. If we don't do this, the cookie will get deleted when the browser closes.

 

Code:

// The time in specified in UTC
document.cookie = "username=Ninja; expires=Fri, 26 Nov 2021 12:00:00 UTC";

Reading cookies in Javascript

We can read the cookies by simply storing the document.cookie value to a variable.

 

Code:

let CookieValue = document.cookie;

 

The issue here, however, is that this will return all the cookies in one string. A semicolon and a space will separate the cookie values.
For example like “cookie1:value1; cookie2:value2; cookie3:value3;”.

 

We can use the split() method to break the string into individual name-value pairs to get around this problem.

 

Code:

// Split cookie string using split() to get all individual name=value pairs in an array
   var cookieArray = document.cookie.split(";");
   
   // Looping through the array elements
   for(var i = 0; i < cookieArray.length; i++) {
   // Split using "=" using    
   var cookieNameValuePair = cookieArray[i].split("=");
       
       // Removing whitespace at the beginning of the cookie name and comparing it with the given string 
       if(name == cookieNameValuePair[0].trim()) {
           // Decode the cookie value and return
           return decodeURIComponent(cookiePair[1]);
       }
   }

Updating cookies in Javascript

Cookies in Javascript can be updated by means of overwriting. Rewriting the same cookie with the new updated values will update cookies in javascript.

 

Code:

// Creating a cookie
document.cookie = "firstName=Ninja; path=/; max-age=" + 123;
// Updating the cookie
document.cookie = "firstName=Ninja; path=/; max-age=" + 456;

Deleting cookies in Javascript

Deleting cookies in Javascript can be done by specifying the expiry parameter to it. Deleting can be done by assigning a date that has already passed. Note that the time has to be given in UTC format and also to specify the path attribute.

 

Code:

document.cookie = "username=; expires=Tue, 07 Jan 1947 00:00:00 UTC; path=/;";

Frequently Asked Questions

1. How to delete cookies using the "max-age" attribute?

Ans:- To delete a cookie, we can rename it using the same name and set its max-age attribute to 0.

 

2. Why are paths important to delete cookies?

Ans:- We should define the cookie path to ensure that we are deleting the right cookie. Also, note that some browsers will not let you delete a cookie if you don't specify the path.

 

3. Explain the samesite attribute.

Ans:- Samesite is a security attribute.  It is used to protect from XSRF (cross-site request forgery) attacks.

Key Takeaways

Cookies in Javascript are used to store data on the user's computer. Cookies in Javascript lets us store information on the user's computers. The amount of data stored is very small, nearly 4KB or so. We can create cookies in javascript using the document.cookie property. We can also read, modify and delete the cookies.

 

If you enjoyed reading this article about Cookies in Javascript, check out Free JavaScript Tutorial By Coding Ninjas and 10 Best JavaScript Certifications In 2021.

Was this article helpful ?
1 upvote

Comments

No comments yet

Be the first to share what you think