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, "\\$&") + '"';
}Inside the snippet
The working surface is the functions parseCookieHeader and serializeCookieValue — everything else is wiring.
The one repetition in this snippet is the loop for (const part of header.split(";")).
What to watch for
- The guard
typeof header !== "string" || header.length === 0short-circuits the flow with an earlyreturnwhen its condition holds.
Using it
Entry signature: export function parseCookieHeader(header)
parseCookieHeader is the public entry point; everything else in the file exists to support it.
Key statements
if (typeof header !== "string" || header.length === 0) return cookies;
return '"' + String(value).replace(/["\\]/g, "\\$&") + '"';
Interactive Tools for This Topic
Set-Cookie ParserParse one or more Set-Cookie header values into the cookie name, value, and attributes like Path, Domain, Expires, Max-Age, Secure, HttpOnly, and SameSite.Accept Header ParserParse an Accept header into media ranges with their quality values and specificity, sorted by preference for content negotiation debugging.Basic & Bearer Auth Header ToolEncode and decode HTTP Authorization Basic and Bearer headers locally with UTF-8 Base64 validation and automatic JWT claim and expiry inspection.CORS Header Policy DebuggerSimulate browser CORS preflight and credential policies against server response headers to pinpoint blocked origins, methods, or headers and fix them.
FAQ
- Any setup needed beyond the language runtime?
- None — the language runtime is the only requirement. The file defines `parseCookieHeader`, `serializeCookieValue` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.