Parse a cookie header
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
Cookieheader value, or the string fromdocument.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
%22into"and corrupt the unquote step. - Server-set
Set-Cookieheaders include attributes likePath,SecureandHttpOnlyafter the main value; this parser is for the client-visibleCookieheader, which has none of them.
Stuck? The javascript course covers everything this challenge needs.
- 1.parses a two cookie header
- 2.keeps the first occurrence of a repeated name
- 3.strips surrounding quotes before decoding
- 4.treats a piece with no equals sign as a flag
- 5.returns an empty object for an empty header
These assertions run in your browser the moment you hit Run. Pass all of them to claim the XP.
Discussion
Sign in to postNo comments yet. Be the first to say something.