Zimt

How to Parse and Decode HTTP Cookie Headers Correctly

· 6 min read · Cookies and Bars

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

Parsing and decoding HTTP cookie headers correctly means extracting each cookie's name, value, and attributes (like Domain, Path, Expires, etc.) from the raw Cookie request header or Set-Cookie response header, and properly handling URL-encoding and special characters. This is essential for web clients, servers, and tools that need to manage sessions or persist state. Before you start, you should have a basic understanding of HTTP headers and a programming language or tool that can handle string manipulation and URL decoding.

What You'll Need

  • A text editor or an integrated development environment (IDE) for writing your parser.
  • Access to a programming language with built-in URL decoding functions (e.g., JavaScript's decodeURIComponent, Python's urllib.parse.unquote, or PHP's urldecode).
  • Sample cookie headers for testing (you can generate them from a browser's developer tools or use the examples in this guide).

Step-by-Step

  1. Identify the header type. The Cookie request header contains cookies sent by the client to the server. The Set-Cookie response header contains cookies sent by the server to the client. They have different formats: Cookie uses a simple list of name=value pairs separated by ;, while Set-Cookie includes attributes after the first pair, also separated by ;.
  2. Split the header into individual cookies. For a Cookie header, split the entire string on the ; character. For a Set-Cookie header, each cookie is a separate header line, so you need to process each line individually. Within a single Set-Cookie line, the first segment before the first ; is the name=value pair, and the rest are attributes.
  3. Trim whitespace. After splitting, trim leading and trailing spaces from each segment. For example, " sessionId=abc123; Path=/ " becomes "sessionId=abc123" and "Path=/".
  4. Separate the name from the value. For each segment, find the first = character. Everything before it is the cookie name, everything after is the value. If there is no =, treat the whole segment as the name with an empty value (though this is rare).
  5. Decode the value (and sometimes the name). Cookie values are often URL-encoded. Use your language's URL decoding function to convert percent-encoded sequences (e.g., %20 for space) into their literal characters. Be careful: the cookie name is usually not encoded, but some clients may encode it, so you can decode it as well if needed. Do not decode the entire cookie string before splitting, because the ; and = characters might be encoded and would confuse the split.
  6. Handle attributes for Set-Cookie. After the first name=value pair, the remaining segments are attributes. Each attribute is a name (like Path, Domain, Expires, Max-Age, Secure, HttpOnly, SameSite) and optionally a value after =. For attributes without a value (like Secure or HttpOnly), set the value to true or an empty string. Parse these into a dictionary or object for easy access.
  7. Validate and store. Ensure the cookie name is not empty and does not contain invalid characters (like semicolons or spaces). Store the parsed cookie in a data structure (e.g., a map) for later use. If multiple cookies have the same name, the last one typically wins, but you may want to keep them all in a list depending on your use case.
  8. Test with edge cases. Test your parser with cookies that have empty values (name=), values with spaces (encoded as %20 or +), values with semicolons (encoded as %3B), and attributes with quoted values (e.g., SameSite="Lax").

Common Mistakes

  • Splitting on ; without considering quoted values. In Set-Cookie, attribute values can be quoted (e.g., SameSite="Lax; Secure"). Splitting naively will break these. You need to respect quotes when splitting.
  • Decoding the entire header before splitting. This can turn encoded semicolons (%3B) into actual semicolons, causing the split to produce wrong segments.
  • Ignoring the difference between Cookie and Set-Cookie. Using the same parser for both will fail because Set-Cookie has attributes that Cookie does not.
  • Not handling the Expires attribute's comma. The Expires attribute contains a comma (e.g., Expires=Wed, 21 Oct 2025 07:28:00 GMT). If you split on ; it's fine, but if you also split on commas you'll break it.
  • Assuming values are always URL-encoded. Some cookies are not encoded. Decoding an already-decoded value can corrupt it (e.g., a literal % becomes %25). You should only decode once, and ideally only if the value contains a %.

Tips

  • Use a well-tested library if possible (e.g., Python's http.cookies, JavaScript's cookie npm package) to avoid reinventing the wheel and to handle edge cases correctly.
  • Always trim whitespace around each segment after splitting. Spaces are common after semicolons.
  • For Set-Cookie, remember that the Expires attribute is a date and should be parsed into a date object if you need to compare it.
  • When storing cookies, consider the scope: path and domain matter for sending them back to the server. Your parser should preserve these attributes.
  • Be aware that cookie names are case-sensitive, but attribute names are not (e.g., path and Path are the same). Normalize attribute names to lowercase for easier handling.

Troubleshooting

My parser returns wrong number of cookies. Check if you are handling multiple Set-Cookie headers correctly. In HTTP, a server can send multiple Set-Cookie headers, each on its own line. If you concatenate them into one string, you'll lose the boundary. Process each header line separately.

Values with semicolons are being split incorrectly. This usually happens when the value is not URL-encoded. The correct fix is to ensure the sender encodes semicolons as %3B. If you cannot control the sender, you may need to implement a more advanced parser that respects quotes and only splits on ; that are outside quotes.

Decoded values contain + instead of spaces. Some URL encoding schemes use + for spaces (application/x-www-form-urlencoded), while standard URL encoding uses %20. Decide which one you expect and use the corresponding decoder. Most cookie implementations use %20, but some older ones use +. You can replace + with %20 before decoding if needed.

My parser fails on the Expires attribute. The Expires attribute contains a comma, which is fine when splitting on semicolons, but if you also split on commas, it breaks. Ensure you only split on semicolons, and do not split on commas.

I'm getting empty cookie names. This can happen if the header starts with a semicolon or has double semicolons. Trim and filter out empty segments before processing.

Frequently Asked Questions

Should I decode the cookie name as well?

Typically, cookie names are not URL-encoded, but they might be in some cases. To be safe, you can decode the name after splitting, but be aware that if the name contains a literal %, decoding could corrupt it. Only decode if you see a % in the name.

How do I handle cookies with the same name?

In the Cookie header, if two cookies have the same name, the browser usually sends both, but the server should treat the first one as the one to use (or the last one, depending on the spec). In practice, you can keep the first or last, but it's safer to store them in a list and let the application decide.

What is the difference between Cookie and Set-Cookie parsing?

Cookie is a simple list of name=value pairs with no attributes. Set-Cookie includes attributes that control the cookie's behavior (like expiration, path, domain, security). You need separate parsers for each.

Can I parse cookies without a library?

Yes, you can write a simple parser as described in this guide. However, for production use, it's better to use a well-tested library to handle edge cases like quoted values and various encoding schemes.

How do I handle cookies that are not URL-encoded?

Not all cookies are URL-encoded. You can check if the value contains a % and only then decode it. Alternatively, you can try to decode and if it fails, use the original value.

What about the Max-Age attribute?

Max-Age is an integer representing seconds until expiration. It is not URL-encoded and should be parsed as an integer. If both Expires and Max-Age are present, Max-Age takes precedence.