Table of contents
1.
Introduction
2.
What is a JavaScript cookie?
3.
How do cookies work?
4.
How to create a Cookie in JavaScript?
5.
Creating cookies in Javascript
6.
Reading cookies in Javascript
7.
Updating cookies in Javascript
8.
Deleting cookies in Javascript
9.
Some attributes related to cookies
10.
Frequently Asked Questions
10.1.
What is the difference between a JavaScript cookie and an HTTP cookie?
10.2.
How to enable cookies in JavaScript?
10.3.
Can I read a cookie with JavaScript?
11.
Conclusion
Last Updated: Aug 17, 2024

Javascript Cookies

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

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. 

What is a JavaScript cookie?

A JavaScript cookie is a small piece of data that a website saves on your computer or mobile device when you visit the site. It's like a little note the website leaves behind so it can remember something about you or your visit when you come back.

When you visit a website, it might save a cookie to remember your preferences, like your preferred language or location. So, the next time you visit, the website can automatically set those preferences without you having to pick them up again. Cookies are also used to keep you logged in to a site, track items in your shopping cart, or even remember your browsing history on that site for targeted advertising.

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

 

How to create a Cookie in JavaScript?

Creating a cookie in JavaScript is pretty simple. A cookie can be created simply by assigning a string to the `document.cookie` object in your JavaScript code. This string typically contains the cookie's name, the value you want to store, and optionally, attributes like expiry date, path, domain, and security flags.

Let's see an example of how to create a cookie:


document.cookie = "username=Rinki; expires=Thu, 18 Dec 2023 12:00:00 UTC; path=/";

Now, let's discuss what each part means:

  • "username=Rinki": This sets the cookie's name to `username` and the value to `JohnDoe`.
  • "expires=Thu, 18 Dec 2023 12:00:00 UTC"**: This part sets when the cookie should expire and be automatically removed. If you don't set this, the cookie will last until the end of the session (when the browser closes).
  • "path=/"**: This sets the path within the site where the cookie is valid. Using `"/"` means the cookie is available throughout the entire site. If you set it to something like `"/blog"`, then the cookie will only be available when the user is in the blog section of your site.

Let's see what each step does:

1. Choose a cookie name and value**: Decide what data you need to store and give the cookie a name.
2. Set an expiry date**: If you want the cookie to last beyond the current session, specify an expiration date. Otherwise, the cookie will disappear when the user closes their browser.
3. Define the path**: Setting the path helps secure where the cookie is used on your site, which can be important for privacy and security.

To see the cookie you've set, you can look in your browser's developer tools under the "Application" tab, where you'll find all cookies listed for the website.

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";
You can also try this code with Online Javascript Compiler
Run Code

 

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";
You can also try this code with Online Javascript Compiler
Run Code

Reading cookies in Javascript

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

 

Code:

let CookieValue = document.cookie;
You can also try this code with Online Javascript Compiler
Run Code

 

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]);
       }
   }
You can also try this code with Online Javascript Compiler
Run Code

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;
You can also try this code with Online Javascript Compiler
Run Code

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=/;";
You can also try this code with Online Javascript Compiler
Run Code

For better understanding, you can try it on an online JS editor.

Must Read Fibonacci Series in JavaScript

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().

Frequently Asked Questions

What is the difference between a JavaScript cookie and an HTTP cookie?

JavaScript cookies are set and accessed via client-side JavaScript, while HTTP cookies are set via server-sent HTTP headers and accessible client-side.

How to enable cookies in JavaScript?

Cookies are enabled by default in browsers. To use them in JavaScript, simply create or modify cookies using document.cookie.

Can I read a cookie with JavaScript?

Yes, you can read cookies in JavaScript using document.cookie, which returns all cookies in a string format for the current domain.

Conclusion

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.

Live masterclass