cookie parsing containing a `=` in value
cmgchess opened this issue · 5 comments
https://github.com/30-seconds/30-seconds-of-code/blob/master/snippets/js/s/parse-cookie.md
if a cookie value contains an =
would this break
const parseCookie = (str) =>
str
.split(';')
.map((v) => {
const equalSignIndex = v.indexOf('=');
const name = v.substr(0, equalSignIndex).trim();
const value = v.substr(equalSignIndex + 1).trim();
return [name, value];
})
.reduce((acc, [name, value]) => {
acc[decodeURIComponent(name)] = decodeURIComponent(value);
return acc;
}, {});
const parseCookie = str =>
str
.split(/;\s(?![^=]+=[^=]+)/) // Split only on semicolons followed by a space, not preceded by an equal sign
.map(v => v.split('='))
.reduce((acc, v) => {
acc[decodeURIComponent(v[0].trim())] = decodeURIComponent(v[1].trim());
return acc;
}, {});
const parseCookie = str => str .split(/;\s(?![^=]+=[^=]+)/) // Split only on semicolons followed by a space, not preceded by an equal sign .map(v => v.split('=')) .reduce((acc, v) => { acc[decodeURIComponent(v[0].trim())] = decodeURIComponent(v[1].trim()); return acc; }, {});
console.log(parseCookie('foo=bar; equation=E%3Dmc%5E2'))
//{ foo: "bar; equation" }
To avoid this problem, you should encode any = characters in cookie values using the encodeURIComponent() function.
document.cookie =
foo=${encodeURIComponent('foo=bar')};
Thanks for opening an issue about this. As shown in the example below the code, if properly encoded, =
is not going to be a problem. parseCookie
is meant to be used in combination with serializeCookie
, explaining the "correct" way to store and retrieve cookie values.