Cookie Header Parser
Parse a Cookie request header into a null-prototype object, handling quoted values, duplicates and RFC 6265 rules.
Code
export function parseCookieHeader(header) {
const cookies = Object.create(null);
if (typeof header !== "string" || header.length === 0) return cookies;
for (const part of header.split(";")) {
const separator = part.indexOf("=");
if (separator < 0) continue;
const name = part.slice(0, separator).trim();
if (!name || name.startsWith("$")) continue;
let value = part.slice(separator + 1).trim();
if (value.length >= 2 && value.startsWith('"') && value.endsWith('"')) {
value = value.slice(1, -1).replace(/\\(["\\])/g, "$1");
}
if (!(name in cookies)) cookies[name] = value;
}
return cookies;
}
export function serializeCookieValue(value) {
return '"' + String(value).replace(/["\\]/g, "\\$&") + '"';
}Report a problem with this exampleOpens a pre-filled issue on GitHub.