How can I store JavaScript objects in cookies?


This tutorial will teach us to store JavaScript objects into the cookies. The cookies are the information of website visitors stored in the text files. There is a particular mechanism to store the cookies of users' browsers. When new visitors visit the website, the server generates the text and sends it to the user. After that, when users allow access to the web page to retrieve the cookies, the server stores all user information in the text files.

Cookies store the user’s search history or other information for a better experience. For example, Google stores the user’s search history to server ads on the web pages according to the user’s interest. YouTube stores cookies to recommend videos with the user’s interest.

Here, we will learn the basic method to store and get cookies to the web server.

Set cookies for the particular web page

First, we will learn to set cookies and get cookies from the browser. We will store the basic information in the form of a string. Also, we set the expiry of the cookies. Users can also add the path to the cookies to know to which location, the cookies have been set up.

Users can follow the below syntax to store cookies and get cookies from the browser.

Syntax

// set cookies in the string format
window.onload = () => { 
   document.cookie = "info=tutorialsPoint; expires=Mon, 27 june 2022 12:00:00 UTC;"; 
}     

//get cookies
Var cookie = document.cookie;

Algorithm (Get a Particular Cookie)

When we store some information to the cookie values, it appends to the previous cookies and doesn’t override the old values. So, when we use the document.cookies, it returns all the stored cookies. We need to fetch the required cookies from all key-values pairs of the cookies.

Here is the algorithm to create a function to fetch the required key value from the cookie.

  • Step 1 − Get the row cookies string format using the document.cookie method.

  • Step 2 − Split the cookies by the semi-colon(;), and it will return the array of the key-value pairs.

  • Step 3 − Iterate through the one-by-one key-value pair to find the required key.

  • Step 4 − While iterating through the key-value pair, remove the space from the front of the key and check that the key matches with our required key or not.

  • Step 5 − If a key is found, return the value for that key. Otherwise, that key-value pair is not stored in the cookies. 

Example

In the below example, we have stored the cookies in the browser using the document.cookie. We have implemented the above algorithm to find the key-value pair from the cookies.

We have used the window.onload() method to store the cookies when the web page loads.

<!DOCTYPE html> <html> <head> <title> Store JavaScript objects in cookies. </title> </head> <body> <h2> Set cookies in JavaScript. </h2> <h4> Getting info and user id stored in cookies from the browser. </h4> <div id="cookies"> </div> <script> let cookie = document.getElementById("cookies"); // function get all cookies function retriveCookie(name) { var name = name + '='; var cookies = decodeURIComponent(document.cookie).split(';'); for (var i = 0; i<cookies.length; i++) { var c = cookies[i]; while (c.charAt(0) == ' ') { c = c.substring(1); } if (c.indexOf(name) == 0) { cookie.innerHTML += "The cookies is - " + c.substring(name.length, c.length) + ". <br/>"; } } } retriveCookie("info"); retriveCookie("uuid"); window.onload = () => { document.cookie = "info=tutorialsPoint; expires=Mon, 27 june 2022 12:00:00 UTC;"; } </script> </body> </html>

In the below output, users can see that we have retrieved the user id and info from the cookies.

Store objects in the Cookies

Now, we have learned how cookies work in JavaScript and how we can store it on the server. The cookies store information in the string format only. If users want to store any other types of data in the cookies, they need to convert it to the string using the stringify() method.

In this section, we will convert the object to a string and store it in cookies. Also, we will retrieve the object from the cookies.

Syntax

Follow the below syntax to store the object in the cookies.

// store object to the cookies
let object = { name: "tutorialsPoint", site: "tutorialsPoint.com", }
document.cookie = 'object=' + JSON.stringify(object);

Example

In the below example, we have stored the object into the cookies after converting it into the string using the JSON.stringify() method. We have used the same algorithm used in the previous section to retrieve the object from the cookies.

<html> <head> <title> Store JavaScript objects in cookies. </title> </head> <body> <h2> Set cookies in JavaScript. </h2> <h4> Set up and getting objects from the browser cookie. </h4> <div id="cookies"></div> <script> let cookie = document.getElementById("cookies"); // function get all cookies function retriveCookie(name) { var name = name + '='; var cookies = decodeURIComponent(document.cookie).split(';'); for (var i = 0; i<cookies.length; i++) { var c = cookies[i]; while (c.charAt(0) == ' ') { c = c.substring(1); } if (c.indexOf(name) == 0) { cookie.innerHTML = "The object in the cookies is - " + c; } } } retriveCookie("object"); window.onload = () => { let object = { name: "tutorialsPoint", site: "tutorialsPoint.com", } document.cookie = 'object=' + JSON.stringify(object); } </script> </body> </html>

Well, we have looked at how cookies work in JavaScript. The cookies send user information to the server. So, maybe hackers can attack and get the user information. Also, cookie stores around 4kb of data in the text files.

Nowadays, every modern browser supports session storage, storing the data in the local computer. The webpage can retrieve the data from the session storage or local store when required rather than fetching the data from the cookies. So, it is recommended to use the session storage rather than cookies as it is more secure, and users can store up to 10MB of data.

Updated on: 09-Aug-2022

9K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements