How to serialize a cookie name-value pair into a Set Cookie header string in JavaScript?


The cookie allows us to store users’ data in the web browser for quick response. For example, when a user opens the profile page in any web application, the web page receives the data from the server. The server also sends the cookies containing the data to store in the web browser. When a user goes on the profile page again, it fetches the data from the cookie rather than fetching it from the server to load the webpage quickly.

To get data browser looks in the cookie first, and if it doesn’t find data stored in the cookie, it requests the server. This tutorial will teach us to serialize a cookie name-value pair into a set cookie header string in JavaScript.

Why do we need to serialize a cookie name-value pair?

We can store a cookie as a key-value pair in the browser, and the cookie doesn’t accept some special characters in the name-value pair, shown below.

\ " / [ ] ( ) < > ? = { } @ , ; : 

So, we need to replace the above characters with the UTF-8 encoding of the special character. For example, we need to replace the space with a ‘%20’ escape sequence.

Use the encodeURIComponent() method to serialize the cookies in JavaScript

The encodeURIComponent() allows developers to encode the string by replacing the special characters with one, two, three or four escape sequences. Here, escape sequences represent the UTF-8 encoding of the character.

Syntax

Users can follow the syntax below to use the encodeURIComponent() method to encode the URI.

encodeURIComponent(key);
encodeURIComponent(value); 

In the above syntax, the encodeURIComponent() method takes the key and value of cookies separately and encodes them by replacing special characters with escape sequences.

Example

In the example below, we have created the serializeCookies() function, which takes the key and value as a parameter. After that, we used the encodeURIComponent() method to encode the key and value separately. Next, we used the string literal to separate its key-value pair ‘=’ character.

In the output, we can observe that the escape sequences replace the special characters.

<html>
<body>
   <h3>Using the <i> encodeURIComponent() </i> method to serialize cookies in JavaScript</h3>
   <div id = "output"> </div>
   <script>
      let output = document.getElementById('output');
      function serializeCookies(key, value) {
         let serializeKey = encodeURIComponent(key);
         let serializeValue = encodeURIComponent(value);
         let serializeCookie = serializeKey + "=" + serializeValue;
         return serializeCookie;
      }
      output.innerHTML += "The key is name, and the value is Shubham Vora. <br>";
      output.innerHTML += "After serializing the cookies key-value pair, result is " + serializeCookies("name", "Shubham Vora");
   </script>
</body>
</html>

Example

In the example below, we have created the arrow function to serialize cookies. We have written the one-liner function to encode the key-value pair and return them. Also, we have used some more special characters in the key-value argument of the serializeCookies() function, and users can observe in the output that every special character has a different escape sequence.

<html>
<body>
   <h3>Using the <i> encodeURIComponent() </i> method to serialize cookies with arrow functions in JavaScript</h3>
   <div id = "output"> </div>
   <script>
      let output = document.getElementById('output');
      const serializeCookies = (key, value) =>
      `${encodeURIComponent(key)}=${encodeURIComponent(value)}`
      output.innerHTML += "The key is key@#$12 and value is Val&^%12#$. <br>";
      output.innerHTML += "After serializing the cookies key-value pair, result is " + serializeCookies("key@#$12", "Val&^%12#$");
   </script>
</body>
</html> 

Example

In the example below, we have created two input fields. One is to take the key as input, and another is to take a value as input. After that, when the user clicks the submit button, it invokes the serializeCookies() function, which accesses the input values and encodes them using the encodeURIComponent() method.

<html>
<body>
   <h3>Using the <i> encodeURIComponent() </i> method to serialize cookies in JavaScript</h3>
   <label for = "key"> Enter Key </label>
   <input type = "text" id = "key">
   <br> <br>
   <label for = "Value"> Enter Value </label>
   <input type = "text" id = "Value">
   <br> <br>
   <div id = "output"> </div>
   <br>
   <button onclick = "serializeCookies()"> Submit </button>
   <script>
      let output = document.getElementById('output');
      function serializeCookies() {
         let key = document.getElementById('key').value;
         let value = document.getElementById('Value');
         output.innerHTML = "The encoded key-value pair is " + `${encodeURIComponent(key)}=${encodeURIComponent(value)}`
      }
   </script>
</body>
</html>

In this tutorial, we learned to serialize the key-value pairs of the cookies using the encodeURIComponent () method. Also, we have seen different examples of serializing cookies. In the last example, users can add custom input, and observe the encoded value of cookies.

Updated on: 28-Feb-2023

797 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements