JavaScript

How to store multiple key-value pairs in Cookies

Cookies store useful information related to the user that can be fetched later. They comprise tiny bits of data kept in a web browser to track user activity. A cookie can contain only one “string” value in JavaScript, and storing multiple key-value pairs requires multiple cookies. However, using multiple cookies can also cause some problems. For instance, if a domain sets the cookie limits as “10“, then you cannot store the information of the 11th user in a new cookie.

In such cases, create a single cookie and store multiple key-value pairs. This approach assists in saving similar information in a cookie and offers several advantages, such as applying an expiration date to multiple key-value pairs at once.

This post discusses the methods of storing multiple key-value pairs in Cookies along with the appropriate examples. So, let’s start!

How to store Multiple key-value pairs in a Cookie

Instead of maintaining multiple cookies, is it highly beneficial to store relevant key-pair values in a single cookie; for instance, rather than creating three cookies for “FullName”, “Class”, “Subject”, we can save these key-value pairs in a single student cookie.

As mentioned earlier, a cookie can only hold a single “key-value” pair at a time. However, to save multiple-key values, you have to follow the below-given instructions:

  • Create a custom object.
  • Convert it to a JSON string with the help of the “stringify()” method.
  • Store the resultant “document.cookie” object.

Now, check out the following example to understand the concept behind using a single cookie for storing multiple-key value pairs.

How to Store values in a Cookie

First of all, in our “index.html” file, three input fields, “FullName”, “Class”, and “Subject,” are added, which will accept the user input as the respective field values.

FullName: <input type="text" class="input" id="fullname">

Class: <input type="text" class="input" id="class">

Subject: <input type="text" class="input" id="subject">

Next, we will add two buttons named: “setCookie” and “getCookie”. The “setCookie” button invokes the “setCookie()” function to set the specified values in a cookie, whereas, the “getCookie” button call the “getCookie()” function to fetch the cookie values:

<input type="button" class="button" value="setCookie" onclick="setCookie()">

<input type="button" class="button" value="getCookie" onclick="getCookie()">

Have a look at our “index.html” file:

In our “project.js” file, we will define the “setCookie()” associated with the “onclick” event of the “setCookie” buttons. The “setCookie()” function will access the values of the input fields by utilizing the “document.getElementById()” method and store them all together in a string “studentInfo”. Then the string “studentInfo” value will be assigned to “document.cookie” object, which results in creating a cookie:

function setCookie() {
 var studentInfo = "FullName=" + document.getElementById("fullname").value + ";Class=" + document.getElementById("class").value + ";Subject=" +document.getElementById("subject").value;

   document.cookie = studentInfo;
   alert("Cookie is created");
}

We will define another function named “getCookie()” in the same file. The “getCookie()” function will check the length of the created cookie in the “if” statement, and then display the created cookie in an alert box. In the other case, if the cookie get expired or deleted, the alert box will state that “Sorry, is Cookie not available”:

function getCookie() {
    if (document.cookie.length != 0) {
        alert(document.cookie);
    }
    else {
        alert("Sorry, is Cookie not available")
    }
} 

Here is how our “project.js” file looks like:

We will save both files and then utilize the VS Code “Live Server” extension to run the application in the browser:

Enter values in the “FullName”, “Class”, and “Subject” input fields and then click on the “setCookie” button:

An alert box will be generated at this point stating that a “Cookie is created”:

Now, click on the “getCookie” button to retrieve the multiple key-value pairs of the created cookie:

As you can see from the output that a single “key-value” pair is displayed, which is “FullName=Sharqa”:

We have tried to store multiple key-value pairs in a cookie; however, the “getCookie()” function only fetched the first-key value pair. This is because JavaScript cookies only permit you to store a single string as a key-value pair in a cookie.

In this situation, you can create a custom JavaScript object, then convert it to a JSON string and store its value (multiple key-value pairs) in a cookie. The below-given example will demonstrate how to perform this operation.

How to Store Multiple key-value pairs in a Cookie using JSON

Move into the “setCookie()” function of the JavaScript file and create a custom object named “object1”. The “object1” will get the values of the added input fields as its properties:

function setCookie() {
  var object1 = {};
  object1.name = document.getElementById("fullname").value;
  object1.class = document.getElementById("class").value;
  object1.subject = document.getElementById("subject").value;

In the next step, we will convert “object1” to a JSON string with the help of “stringify()” method and store the resultant string “document.cookie” object:

var jsonString = JSON.stringify(object1);

document.cookie = jsonString;

alert("Cookie is created");

}

To retrieve the multiple key-value pair stored as a string in the “document.cookie” object, we will use the “JSON.parse()” method. The “JSON.parse()” method will parse the “document.cookie” into a JSON object. Lastly, multiple key-value pairs will be displayed in an alert box:

function getCookie() {
if (document.cookie.length != 0) {
    var obj = JSON.parse(document.cookie);
    alert("FullName=" + obj.name + " " + "Class=" + obj.class + " " + "Subject=" + obj.subject);
    }
  else {
    alert("Cookie not available");
    }
} 

Now, again open up the “index.html” page in the browser and enter values in the specified fields:

Clicking on the “setCookie” button will let you know that a cookie is created:

In the next step, click on the “getCookie” button, which is present next to the “setCookie”:

The generated alert box signifies that we have successfully stored multiple key-value pairs in a single cookie:

You can also utilize multiple cookies for the same purpose. However, we do not recommend you use this approach as it makes it challenging to maintain multiple cookies.

Conclusion

To store multiple key-value pairs in a cookie, you have to create a custom object, convert it to a JSON string with the help of the “stringify()” method, and store the resultant “document.cookie” object. This approach assists in saving similar information in a cookie and offers several benefits, such as applying an expiration date to multiple key-value pairs at once. This write-up discussed the procedure to store multiple key-value pairs in Cookies along with the suitable examples.

About the author

Sharqa Hameed

I am a Linux enthusiast, I love to read Every Linux blog on the internet. I hold masters degree in computer science and am passionate about learning and teaching.