How to read a cookie using JavaScript?


In this article, we will learn how to read cookies in javascript, and how we can use it to implement certain features such as user tracking, user preference, personalized experience, etc.

Cookies are small pieces of data stored in a user's web browser. In javascript, we can read cookies using document's cookie property and extract the desired information using destructuring.

Let’s look at some of the examples to understand the concept better −

Example 1 - Reading All Cookies

In this example, we will −

  • read all cookies by accessing the document.cookie property and log them to the console.

  • This shows us how to obtain a string containing all the cookies.

Filename - index.html

<html>
<head>
   <title>How to read a cookies</title>
   <script>
      document.cookie = "session=123456789";

      function readAllCookies() {
         let cookies = document.cookie;
         console.log(cookies);
      }

      readAllCookies();
   </script>
</head>
<body>
   <h1>Read All Cookies</h1>
</body>
</html>

Output

The result will like the image below.

Example 2 - Reading a Specific Cookie

In this example, we will −

  • define a getCookie function that gives us the value of a specific cookie.

  • We will split the document.cookie string into an array of individual cookies, iterate over them, and check for a matching cookie name.

  • If the cookie got found, we will return the decoded value.

  • We will then log the cookie to the console.

Filename - index.html

<html>
<head>
   <title>How to read a cookie using JavaScript?</title>
   <script>
      document.cookie = "username=John Doe";
      document.cookie = "profession=Software Engineer";

      function getCookie(cookieName) {
         let cookies = document.cookie;
         let cookieArray = cookies.split("; ");
      
         for (let i = 0; i < cookieArray.length; i++) {
            let cookie = cookieArray[i];
            let [name, value] = cookie.split("=");
           
            if (name === cookieName) {
               return decodeURIComponent(value);
            }
         }
         
         return null;
      }

      let username = getCookie("username");
      console.log(username);
   </script>
</head>
<body>
   <h1>Read Specific Cookie</h1>
</body>
</html>

Output

The result will like the image below.

Conclusion

Reading cookies enables us to have access to browser−stored user−specific data like preferences, session IDs, or login tokens. These values can then be applied to a variety of online applications, such as customising user interfaces, adding user−specific features, or monitoring website activity. We learned how to read a cookie in javascript using different methods and saw some examples explaining the same.

Updated on: 16-Aug-2023

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements