Open In App

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

Improve
Improve
Like Article
Like
Save
Share
Report

To parse HTTP Cookie header we will spilt the cookies data and create objects from the key-value extracted from cookies. Cookies are simply small text files that a web server sends to the user’s browser. They contain the following data.

  • Name-value pair with actual data.
  • The expiry date for when the cookie becomes invalid.
  • 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: This code defines a cookieParser function that takes a cookie string as input and returns an object containing the parsed key-value pairs. The provided example usage with dummyCookieString demonstrates how the function works.The console.log statements at the end print the values of specific cookies (‘gfg’ and ‘foo’) from the parsed object.

Javascript




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']}.`);


Output

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


Last Updated : 06 Mar, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads