Parse and Set Cookies

Write the code, see it run, pass the checks.

The problem

  • medium
  • Code

Write parseCookies(header), which reads a Cookie request header such as "theme=dark; session=abc123" into an object of names and values. Split it at each ";" and trim the spaces around each name and value. Each pair splits at its first "=", so values may contain "="; skip pairs with no "=" or an empty name, and if a name comes twice, keep the first. If a value is wrapped in double quotes, remove them. Then decode the value with decodeURIComponent, but keep it as it is if decoding throws. Then write serializeCookie(name, value, options), which builds a Set-Cookie header value: the name, "=" and the value encoded with encodeURIComponent, then, separated by "; ", each attribute that options gives, in this order: Max-Age= with options.maxAge in seconds, rounded down and written even when it's 0; Domain= with options.domain; Path= with options.path; Expires= with options.expires, a Date, in its toUTCString() form; HttpOnly and Secure, each only when its option is true; and SameSite= with options.sameSite written as Strict, Lax or None, whatever its letter case. Throw a TypeError if the name is empty or contains a space, ";", "," or "=", if sameSite is any other word, or if it is None without secure, a cookie browsers reject. options may be left out.

Your code must pass

  • Parses a Cookie header into an object
  • Decodes values and strips quotes
  • Skips broken pairs and keeps the first of a name
  • Serializes a name and encoded value
  • Adds attributes in order
  • Rejects bad names and SameSite=None without Secure