Sunday, September 22, 2024
Google search engine
HomeLanguagesJavascriptHow to parse HTTP Cookie header and return an object of all...

How to parse HTTP Cookie header and return an object of all cookie name-value pairs in JavaScript ?

Cookies are simply small text files that a web server sends to the user’s browser. They contain the following data.

  1. Name-value pair with actual data.
  2. The expiry date for when the cookie becomes invalid.
  3. Domain and path of the server it should be sent to.

Approach: To retrieve all the stored cookies in JavaScript, we can use the document.cookie property but this property returns a single string in which the key-value pair is separated by a “;”. It would be great if we can store the key-value pair into an object as it would make the retrieval process much easier. JavaScript does not provide any methods for such a scenario. So let’s work around this problem.

We need to create a function that will parse the cookie string and would return an object containing all the cookies. This would be a simple process with the following steps.

  1. Get each individual key-value pair from the cookie string using string.split(“;”).
  2. Separate keys from values in each pair using string.split(“=”).
  3. Create an object with all key-value pairs and return the object.

Example: Refer to the comments in the following code for better understanding.

Javascript




<script>
    function cookieParser(cookieString) {
      
        // Return an empty object if cookieString
        // is empty
        if (cookieString === "")
            return {};
      
        // Get each individual key-value pairs
        // from the cookie string
        // This returns a new array
        let pairs = cookieString.split(";");
      
        // Separate keys from values in each pair string
        // Returns a new array which looks like
        // [[key1,value1], [key2,value2], ...]
        let splittedPairs = pairs.map(cookie => cookie.split("="));
      
      
        // Create an object with all key-value pairs
        const cookieObj = splittedPairs.reduce(function (obj, cookie) {
      
            // cookie[0] is the key of cookie
            // cookie[1] is the value of the cookie 
            // decodeURIComponent() decodes the cookie 
            // string, to handle cookies with special
            // characters, e.g. '$'.
            // string.trim() trims the blank spaces 
            // auround the key and value.
            obj[decodeURIComponent(cookie[0].trim())]
                = decodeURIComponent(cookie[1].trim());
      
            return obj;
        }, {})
      
        return cookieObj;
    }
      
    let dummyCookieString = 
        "username=John; gfg=GeeksForGeeks; foo=education";
      
    // Pass document.cookie to retrieve actual cookies
    let cookieObj = cookieParser(dummyCookieString);
      
    console.log(`cookie gfg has value ${cookieObj['gfg']}.`);
    console.log(`cookie foo has value ${cookieObj['foo']}.`);
</script>


Output:

cookie gfg has value GeeksForGeeks.
cookie foo has value education.

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments