← All Exercises
Parse and Serialize Cookie Strings
basicjavascript
Background
Cookies remain a common browser storage mechanism for sessions and preferences. The document.cookie string has awkward delimiters, so parsing and building it correctly is a recurring front-end task.
Problem
Implement two helpers: parseCookies(header) that turns a semicolon-separated cookie string into an object, keeping the first value for duplicate names and decoding percent escapes safely, and serializeCookie(name, value, options) that appends Path, Max-Age, SameSite, and Secure attributes.
Input
A JSON object whose action is parse (with cookie) or serialize (with name, value, options).
Output
For parse, a JSON object of cookie names to decoded values. For serialize, the Set-Cookie style attribute string.
Sample tests
Sample 1
Input: {"action":"parse","cookie":"a=1; b=hello%20world; c"}Expected: {"a":"1","b":"hello world","c":""}Sample 2
Input: {"action":"parse","cookie":"id=1; id=2; theme=dark"}Expected: {"id":"1","theme":"dark"}Sample 3
Input: {"action":"serialize","name":"token","value":"a b","options":{"path":"/","maxAge":3600,"sameSite":"Lax","secure":true}}Expected: token=a%20b; Path=/; Max-Age=3600; SameSite=Lax; Secure
Sample 4
Input: {"action":"parse","cookie":"bad=%E0%A4%A"}Expected: {"bad":"%E0%A4%A"}Your solution
Learning objective
Learn cookie header syntax, safe percent-decoding, and attribute serialization for browser storage.