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 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 serve ads on web pages according to the user's interest. YouTube stores cookies to recommend videos based on the user's interest.

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

Set Cookies for the 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.

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 raw 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: Basic Cookie Operations

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 to get specific cookie
      function retrieveCookie(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 cookie is -  " + c.substring(name.length, c.length) + ". <br/>";
            }
         }
      }
      
      // Store cookies when page loads
      window.onload = () => { 
         document.cookie = "info=tutorialsPoint; expires=Mon, 27 june 2022 12:00:00 UTC;";
         document.cookie = "uuid=12345; expires=Mon, 27 june 2022 12:00:00 UTC;";
         
         // Retrieve cookies after storing
         retrieveCookie("info");
         retrieveCookie("uuid");
      }
   </script>
</body>
</html>

Store Objects in the Cookies

Now, we have learned how cookies work in JavaScript and how we can store them 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 JSON.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: Storing and Retrieving Objects

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 to get specific cookie
      function retrieveCookie(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) {
               let objectString = c.substring(name.length, c.length);
               let parsedObject = JSON.parse(objectString);
               cookie.innerHTML = "The object in the cookies is - " + JSON.stringify(parsedObject, null, 2);
            }
         }
      }
      
      window.onload = () => {
         let object = { name: "tutorialsPoint", site: "tutorialsPoint.com" };
         document.cookie = 'object=' + JSON.stringify(object);
         
         // Retrieve object after storing
         retrieveCookie("object");
      }
   </script>
</body>
</html>

Key Points

  • Cookies can only store strings, so objects must be converted using JSON.stringify()

  • Use JSON.parse() to convert the string back to an object when retrieving

  • Cookies have a size limit of approximately 4KB

  • Always set an expiry date for cookies to avoid them persisting indefinitely

  • Cookie data is sent with every HTTP request to the domain

Modern Alternatives

While cookies work for storing JavaScript objects, modern browsers support more efficient storage options:

  • localStorage - Stores up to 10MB, persists until manually cleared

  • sessionStorage - Stores data for the browser session only

  • IndexedDB - For large amounts of structured data

These alternatives are more secure since data doesn't travel with every HTTP request.

Conclusion

JavaScript objects can be stored in cookies by converting them to strings using JSON.stringify() and parsed back using JSON.parse(). However, consider modern storage alternatives like localStorage for better performance and security.

Updated on: 2026-03-15T23:18:59+05:30

13K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements