Cookie Header Parser

Parse a Cookie request header into a null-prototype object, handling quoted values, duplicates and RFC 6265 rules.

JavascriptData Fetching

Code

javascriptsnippet
20 lines
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 === 0 short-circuits the flow with an early return when 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

FAQ

Any setup needed beyond the language runtime?
None — the language runtime is the only requirement. The file defines `parseCookieHeader`, `serializeCookieValue` at load time.