How to read a cookie using JavaScript?

In this article, we will learn how to read cookies in JavaScript and use them for features like user tracking, user preferences, and personalized experiences.

Cookies are small pieces of data stored in a user's web browser. In JavaScript, we can read cookies using the document's cookie property and extract specific values using string manipulation techniques.

Understanding document.cookie

The document.cookie property returns all cookies as a single semicolon-separated string. Each cookie appears as name=value pairs.

Example 1: Reading All Cookies

This example demonstrates how to access all cookies stored for the current domain:

<!DOCTYPE html>
<html>
<head>
   <title>Reading All Cookies</title>
</head>
<body>
   <h1>Read All Cookies</h1>
   <script>
      // Set some cookies first
      document.cookie = "session=123456789";
      document.cookie = "theme=dark";
      
      function readAllCookies() {
         let cookies = document.cookie;
         console.log("All cookies:", cookies);
         return cookies;
      }
      
      readAllCookies();
   </script>
</body>
</html>
All cookies: session=123456789; theme=dark

Example 2: Reading a Specific Cookie

This example shows how to extract the value of a specific cookie by name:

<!DOCTYPE html>
<html>
<head>
   <title>Reading Specific Cookie</title>
</head>
<body>
   <h1>Read Specific Cookie</h1>
   <script>
      // Set multiple cookies
      document.cookie = "username=John Doe";
      document.cookie = "profession=Software Engineer";
      document.cookie = "language=English";
      
      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; // Cookie not found
      }
      
      let username = getCookie("username");
      let profession = getCookie("profession");
      let nonExistent = getCookie("age");
      
      console.log("Username:", username);
      console.log("Profession:", profession);
      console.log("Age:", nonExistent);
   </script>
</body>
</html>
Username: John Doe
Profession: Software Engineer
Age: null

Enhanced Cookie Reader Function

Here's an improved version that handles edge cases and provides better error handling:

<!DOCTYPE html>
<html>
<head>
   <title>Enhanced Cookie Reader</title>
</head>
<body>
   <h1>Enhanced Cookie Reader</h1>
   <script>
      // Set cookies with different values
      document.cookie = "user_id=12345";
      document.cookie = "preferences=color:blue,size:large";
      
      function getCookieAdvanced(name) {
         if (!name) return null;
         
         const namePattern = name.replace(/[.*+?^${}()|[\]\]/g, '\$&');
         const regex = new RegExp('(?:^|; )' + namePattern + '=([^;]*)');
         const match = document.cookie.match(regex);
         
         return match ? decodeURIComponent(match[1]) : null;
      }
      
      function getAllCookiesAsObject() {
         const cookies = {};
         if (document.cookie) {
            document.cookie.split('; ').forEach(cookie => {
               const [name, value] = cookie.split('=');
               cookies[name] = decodeURIComponent(value);
            });
         }
         return cookies;
      }
      
      console.log("User ID:", getCookieAdvanced("user_id"));
      console.log("Preferences:", getCookieAdvanced("preferences"));
      console.log("All cookies as object:", getAllCookiesAsObject());
   </script>
</body>
</html>
User ID: 12345
Preferences: color:blue,size:large
All cookies as object: {user_id: "12345", preferences: "color:blue,size:large"}

Key Points

  • document.cookie returns all cookies as a semicolon-separated string
  • Use split() to separate individual cookies
  • Always use decodeURIComponent() when reading cookie values
  • Cookie names are case-sensitive
  • Returns null or empty string if cookie doesn't exist

Common Use Cases

  • Session Management: Reading session IDs for user authentication
  • User Preferences: Retrieving saved settings like theme or language
  • Shopping Carts: Accessing stored cart items
  • Analytics: Reading tracking cookies for user behavior analysis

Conclusion

Reading cookies in JavaScript involves using document.cookie and parsing the returned string to extract specific values. Always handle cases where cookies might not exist and use decodeURIComponent() for proper value retrieval.

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

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements