How to parse HTTP Cookie header and return an object of all cookie name-value pairs in JavaScript ?
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.
- Get each individual key-value pair from the cookie string using string.split(“;”).
- Separate keys from values in each pair using string.split(“=”).
- 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) {
if (cookieString === "" )
return {};
let pairs = cookieString.split( ";" );
let splittedPairs = pairs.map(cookie => cookie.split( "=" ));
const cookieObj = splittedPairs.reduce( function (obj, cookie) {
obj[decodeURIComponent(cookie[0].trim())]
= decodeURIComponent(cookie[1].trim());
return obj;
}, {})
return cookieObj;
}
let dummyCookieString =
"username=John; gfg=GeeksForGeeks; foo=education" ;
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
Share your thoughts in the comments
Please Login to comment...