AniUI Academy

Parse a cookie header

mediumDOM & Utilities+250 XPPractice

Cookies arrive as one string, "theme=dark; sid=abc123", whether from document.cookie in the browser or the Cookie header on the server. Every auth helper starts with a parser like this.

Implement parseCookies(header) returning a plain object. Split the string on ; and trim each piece, skipping pieces that are empty. Split each piece on its **first** =; a piece with no = is a flag whose value is the empty string "".

Trim the raw value, and if it both starts and ends with a double quote, strip those two quotes — this happens before any decoding, so token="x y" yields x y. Then decode the key and the value with decodeURIComponent, falling back to the raw text if decoding throws.

When the same name appears twice, the **first** occurrence wins, which is how the browser resolves it. An empty header returns {}.

Arguments

headerstring
A Cookie header value, or the string from document.cookie. An empty string returns {}.

Returns

Record<string, string> — A plain object of decoded cookie names to decoded values. Repeated names keep the first occurrence.

Examples

parseCookies("theme=dark; sid=abc123");
// => { theme: "dark", sid: "abc123" }

The common case: semicolon-separated pairs.

parseCookies('name=%22Ada%20Lovelace%22; token="x y"');
// => { name: '"Ada Lovelace"', token: "x y" }

Surrounding double quotes are stripped before decoding.

parseCookies("a=1; a=2");
// => { a: "1" }

First occurrence wins, matching the browser's lookup.

What it has to do

  • Split on ;, trim each piece, and skip empty pieces.
  • Split each piece on the first =; a piece with no = gets the value "".
  • Strip surrounding double quotes from the raw value before decoding.
  • Decode keys and values with decodeURIComponent, tolerating malformed escapes.
  • Keep the first occurrence when a name is repeated, and return {} for an empty header.

Notes

  • Order of operations is the whole problem: trim, then unquote, then decode. Decoding first can turn %22 into " and corrupt the unquote step.
  • Server-set Set-Cookie headers include attributes like Path, Secure and HttpOnly after the main value; this parser is for the client-visible Cookie header, which has none of them.
Asked atGoogle

Stuck? The javascript course covers everything this challenge needs.

Try it yourself
Loading playground...
5 tests · +250 XP

Discussion

Sign in to post
Sign in to join the conversation.Sign in

No comments yet. Be the first to say something.