How to create and read the value from cookies


Overview

Cookies are the temporary storage, which stores the user data in the form of key value pairs. Cookies are stored on the clients systems. When a user visits a website then a request is sent to the server to which the website is hosted, then it loads the content and sends it back to the receiving end(receiver is the client or a user). The server sends the cookie to store the user data for its future use. But it all depends upon the user whether he wants to store the login credentials to the cookie or not. In the edible cookie a chocolate is filled inside the donut same as in the web cookie cookie filled is the donut and the chocolate filled is the value of the cookie.

Syntax

The syntax to create a cookie is −

document.cookie= cookieName + cookieValue + cookieExpiry;
  • cookieName  It is the name of the cookie which stores the value to it. For example: username, address and many more fields.

  • cookieValue  It is the value which is stored in the key of the cookie name. For example: Alex, United States, etc.

  • cookieExpiry  It is the numerical value, it states that for how many days the cookie will remain alive in the client's browser.

Algorithm

Step 1  Create a HTML file in your text editor such as sublime editor or visual studio code editor. Add the HTML boilerplate in the HTML file.

Step 2  Now add an onload() event function to the body tag of the HTML document. Pass a function to the onload() function with the name as “myFunc()”.

<body onload="myFunc()"></body>

Step 3  Now create a script.js file in the same folder in which we have created a HTML file. Link the script,js file to the HTML document before the end of the body tag.

<script src="script.js"></script>

Step 4  Now create an arrow function in the script file which checks whether the cookie exists or not in the client system. The function name should be the same as the name we had passed in the onload() function in the body tag as an attribute.

myFunc = () => {
   var cl = readCookiesValue("clients_Name");
   var ad = readCookiesValue("clients_address")
   if (cl != "") {
      alert("Welcome " + cl +" from "+ad + “ to the server”);
   } else {
      cl = prompt("Write your name", "");
      ad = prompt("Write your address", "");
      if (cl != "" && cl != null) {
         createCookies("clients_Name", cl, 30);
         createCookies("clients_address", ad, 30);
      }
   }
}

Step 5  Now create an arrow function with the name as “createCookies” which will create a cookie for the user. The create cookie will take the three parameters as cookie name, cookie value and cookie expiry. The cookie will be created by using the “document.cookie” syntax.

createCookies = (ckName, ckValue, ckExpiry) => {
   var cdate = new Date();
   date.setTime(cdate.getTime() + (ckExpiry * 24 * 60 * 60 * 1000));
   var expires = "expires=" + cdate.toGMTString();
   document.cookie = ckName + "=" + ckValue + ";" + expires + ";path=/";
}

Step 6  Now after the cookies are created, create an arrow function with the name “readCookiesValue” which will read the present cookie in the browser, this will take the cookie name as the parameter and will return the value of cookie.

readCookiesValue = (cookieName) => {
   var name = cookieName + "=";
   var decoded_cookie = decodeURIComponent(document.cookie);
   var dcooks = decoded_cookie.split(';');
   for (let i = 0; i < dcooks.length; i++) {
      var c = dcooks[i];
      while (c.charAt(0) == ' ') {
         c = c.substring(1);
      }
      if (c.indexOf(name) == 0) {
         return c.substring(name.length, c.length);
      }
   }
   return "";
}

Step 7  The read and create functions for the cookies are created successfully.

Example

In this example we have created a function which will check whether the cookie is present in the client browser or not, if the cookie is not present in the clients browser then it will create the cookie for the current client and will store it further for the future till the cookie is not expired.

<html>
<head>
   <title>Create and read cookie value</title>
</head>
<body onload="myFunc()">
   <h1 style="text-align: center;color: green;" onload="myfunc()">Welcome to tutorialspoint.com</h1>
   <script src="script.js"></script>
   <script>
      myFunc = () => {
         var client = readCookiesValue("clients_Name");
         var adress = readCookiesValue("clients_address")
         if (client != "") {
            alert("Hello " + client +" from "+adress);
         } else {
            client = prompt("Enter your name", "");
            adress = prompt("Enter your adress", "");
            if (client != "" && client != null) {
               createCookies("clients_Name", client, 30);
               createCookies("clients_address", adress, 30);
            }
         }
      }
      createCookies = (cookieName, cookieValue, cookieExpiry) => {
         var date = new Date();
         date.setTime(date.getTime() + (cookieExpiry * 24 * 60 * 60 * 1000));
         var expires = "expires=" + date.toGMTString();
          document.cookie = cookieName + "=" + cookieValue + ";" + expires; + ";path=/";
      }
      readCookiesValue = (cookieName) => {
         var name = cookieName + "=";
         var decoded_cookie = decodeURIComponent(document.cookie);
         var dcooks = decoded_cookie.split(';');
         for (let i = 0; i < carr.length; i++) {
            var c = carr[i];
            while (c.charAt(0) == ' ') {
               c = c.substring(1);
            }
            if (c.indexOf(name) == 0) {
               return c.substring(name.length, c.length);
            }
         }
         return "";
      }
   </script>
</body>
</html>

Output

The given below images shows the output of the above example in which we have built a read and create cookie functions. So when the user loads the above example in his browser for the first time the function will check whether there are cookies present for the current request if not present, then the client will get a prompt alert to write his name, after the client write his name to the box he will get a another prompt alert to write his city name and then he will get redirect to the main content. So when the client loads the web page the second time the function will again check for the cookies this time the cookies are present in the client browser so the client will get a welcome message of greeting “Hello clientName from cityName” which you can see in thirds image.

Conclusion

The cookies are used in all of the applications such as irctc and other website for booking reservations and browsing purposes. They allow the user to be logged to the websites as long as the cookies are alive. Sometimes cookies are also dangerous to the system as there may be some harmful or pirated sites which create the cookies to spy on your system, so it is requested to not to accept the cookies from the websites which are not known.

Updated on: 14-Jul-2023

232 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements