Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.
Parse a request Cookie header by splitting it at semicolons, trimming spaces and tabs, and splitting each non-empty pair at its first equals sign. Keep duplicate names and the original values. Decode a value only when the application that created it specifies how. A Cookie header is not the same as Set-Cookie: it does not carry cookie attributes such as Path, Domain, or HttpOnly.
What a Cookie header contains
An HTTP cookie has a two-part lifecycle. A server can send a response header named Set-Cookie to ask a user agent to store a cookie. When a stored cookie applies to a later request, the user agent may send its name and value in a request header named Cookie. RFC 6265 defines both fields and the rules connecting them: RFC 6265.
A typical request header looks like this:
Cookie: session_id=abc123; theme=dark; preference=a=b=c
After removing the field name and colon, the header value is a sequence of cookie pairs separated by a semicolon and a space: name=value; name2=value2. The equals sign inside preference=a=b=c belongs to its value. Split only on the first equals sign in each pair.
Recommended Free Tools
That is syntax, not a promise about what the values mean. RFC 6265 leaves cookie-value semantics to the application. A value may be an opaque session identifier, a signed token, or data serialized in a format chosen by the site. The parser should extract it without guessing its meaning.
#1 Best Overall
Parse the header without losing information
- Pass the header value, not the field label. Give the parser the text after
Cookie:, such assession_id=abc123; theme=dark. If your server framework already gives you a parsed cookie collection, check its documented behavior before parsing again. - Split on semicolons. Under the RFC request grammar, each segment is a cookie pair. A semicolon is a delimiter, not part of the value.
- Trim surrounding spaces and tabs. This avoids treating the separator’s optional whitespace as part of a name or value.
- Split each segment at its first equals sign. Text before that sign is the name; everything after it is the value. Do not split a value such as
a=b=cinto several fields. - Retain duplicates and ordering. Store pairs in an ordered list, or map each name to a list of values. Do not silently collapse duplicates into one value: cookies with the same name can arise from different paths or domains, and the request header does not identify which scope produced each pair.
- Handle malformed segments deliberately. A segment without an equals sign is not a valid name-value pair. Reject it, record it for diagnostics, or skip it according to your application’s policy; do not quietly reinterpret it as a valid cookie.
An empty or absent header produces an empty collection. That does not necessarily indicate an error: the user agent may have no applicable cookies, may choose not to send them, or may omit them because of privacy settings.
Language-neutral parser outline
parseCookieHeader(header):
result = ordered list of (name, value)
for segment in split(header, ';'):
segment = trim_spaces_and_tabs(segment)
if segment == '': continue
i = index_of_first('=', segment)
if i < 0:
handle_malformed_segment(segment)
continue
name = trim_spaces_and_tabs(segment[0:i])
value = trim_spaces_and_tabs(segment[i+1:])
result.append((name, value))
return result
Example: preserve duplicates and embedded equals signs
Given id=first; theme=dark; id=second; token=a=b, the parsed pairs are (id, first), (theme, dark), (id, second), and (token, a=b). A plain dictionary keyed by name would discard one of the id pairs unless it deliberately stores multiple values.
A runnable Python parser
This example returns an ordered list of pairs, preserving repeated names. It accepts either a header value or a full field string beginning with Cookie:; malformed non-empty segments raise an error rather than being silently altered.
Outdated Drivers Are Slowing You Down
One free scan finds every outdated or missing driver and matches the right update for your exact hardware.Free scan · exact hardware matchWindows Errors? Fix Them Before They Spread
Repair common Windows errors and clear accumulated junk for a smoother, more stable PC - no reinstall needed.Free scan · no reinstalldef parse_cookie_header(header):
if header is None or header == "":
return []
# Accept a complete field line as a convenience, but do not require it.
if header[:7].lower() == "cookie:":
header = header[7:]
pairs = []
for raw_segment in header.split(";"):
segment = raw_segment.strip(" t")
if not segment:
continue
equals = segment.find("=")
if equals < 0:
raise ValueError(f"Malformed cookie pair: {segment!r}")
name = segment[:equals].strip(" t")
value = segment[equals + 1:].strip(" t")
if not name:
raise ValueError("Cookie name must not be empty")
pairs.append((name, value))
return pairs
header = "Cookie: id=first; theme=dark; id=second; token=a=b"
print(parse_cookie_header(header))
# [('id', 'first'), ('theme', 'dark'), ('id', 'second'), ('token', 'a=b')]
This is a small syntax parser, not a complete HTTP validation library. Apply your server framework’s header-size limits and input-validation policy at the request boundary. If you need to validate cookie-octet restrictions or handle non-standard client behavior, use a library whose documented behavior matches that need.
Should you URL-decode a cookie value?
Not automatically. Percent-encoding is common, but it is not required by RFC 6265. Decode only when the application contract says the producer percent-encoded the value. Otherwise, changing the value may break signature verification, turn an opaque identifier into different bytes, or cause your program to treat text as a format it was never meant to use.
- Keep the raw value. Preserve it for signature checks and for any logic that expects the original representation. Decide separately whether and how it can safely be logged; session values and tokens may be credentials.
- Decode once, not repeatedly. Repeated decoding can transform data unexpectedly. For instance, a percent-encoded percent sign can become a new escape sequence if decoded more than once.
- Choose a malformed-escape policy. Languages differ in how strictly their URL-decoding functions handle invalid percent escapes or invalid character encodings. For credentials or signed values, prefer an explicit failure over silently producing a different value.
- Do not infer Base64, JSON, or encryption. Use those decoders only when the application specifies that encoding or serialization. Parsing a cookie pair does not reveal whether its value is signed, encrypted, or meaningful to the server.
If you own both ends of the exchange, document the encoding, character set, and decoding sequence as part of the cookie’s application contract. For arbitrary data, RFC 6265 recommends encoding it for compatibility rather than assuming it can be placed raw in a cookie value.
Cookie and Set-Cookie are different formats
A request’s Cookie header contains the name-value pairs the user agent chose to send. It does not include the attributes that accompanied the cookie when it was set. A response’s Set-Cookie field contains a cookie pair followed by attributes such as Domain, Path, Expires, Max-Age, Secure, HttpOnly, SameSite, or Partitioned. See the references for Cookie and Set-Cookie.
Consequently, you cannot read a request header and determine the original cookie’s expiry, path, domain, or whether it was marked Secure or HttpOnly. The header does not carry those facts. The same-name duplicate pairs also cannot be reliably attributed to their original scopes from the request header alone.
Rank #3
Do not feed Set-Cookie to the parser above. Each response Set-Cookie field represents a separate cookie, and an Expires attribute can contain a comma in its date. Treating commas as a safe way to split combined fields can therefore break the data; RFC 6265 also warns that folding multiple Set-Cookie fields can change their semantics. Use an HTTP library’s separate Set-Cookie handling rather than adapting the request-cookie split rule.
Browser and JavaScript visibility limits
In a browser, document.cookie exposes a semicolon-separated string of cookies available to the page, but it does not expose cookies marked HttpOnly. It is not a view of every cookie in the browser’s storage. A browser may also omit a Cookie request header because of privacy controls or because no stored cookie applies. See MDN’s Document.cookie reference and Cookie header reference.
Frontend JavaScript also cannot inspect the Set-Cookie response header through Fetch: it is a forbidden response-header name. If you need to confirm what a server set, use an appropriate server-side diagnostic or browser developer tools rather than expecting client-side Fetch code to read that header.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
Or skip the browser setup
For visual QA of a page’s cookie-consent experience—not parsing its HTTP headers—ScreenshotNeo can capture a URL through a single API request. It accepts cookie or consent banners as a visitor and removes more than 60 known consent platforms, newsletter popups, and chat widgets before capture; each step can be turned off. This does not expose the page’s request Cookie header or replace the parser above.
Example cURL request (see the ScreenshotNeo API documentation):
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
- Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed; the response includes
X-Page-VerdictandX-Billedheaders. - An MCP server offers
take_screenshot,get_page_info, andcapture_pdftools for Claude, Cursor, and other MCP clients. - The Free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000. Every feature is on every plan.
Sign up free for 1,000 screenshots a month, with no card required.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Troubleshooting common parsing problems
The parsed value is truncated at an equals sign
Cause: The parser split on every equals sign. Fix: Find the first equals sign only; retain the entire remainder as the value.
Do these 3 things before closing this tab:
1Scan for outdated or missing drivers - takes under a minute2Clear out junk files and repair common Windows errors3Fix the driver behind crashes, sound loss and screen glitchesA value looks encoded or unreadable
Cause: The application may use percent-encoding, Base64, a signed token, or an opaque identifier. There is no universal cookie-value decoder. Fix: Check the producer’s contract, retain the raw value, and apply only the documented decoder.
The parser loses a cookie with a repeated name
Cause: A map keyed by name overwrote an earlier pair. Fix: Use an ordered list of pairs or map names to lists, and apply application-specific selection rules only when you know what the duplicates mean.
Best Value
- Used Book in Good Condition
Path, Domain, or HttpOnly is missing
Cause: Those are Set-Cookie attributes, not fields in a request Cookie header. Fix: Inspect the relevant response’s Set-Cookie data or browser storage with an appropriate tool; do not infer attributes from the request pair.
No Cookie header arrived
Cause: There may be no applicable cookie, or the user agent may omit cookies because of privacy settings or request context. Fix: Check the request actually received by the server and the relevant browser settings. Treat an absent header as an empty collection unless your application has a separate requirement that makes it an error.
Quick wins for a faster PC:
Repair Windows errors before they cause bigger problemsFix Now →Scan for outdated or missing drivers - takes under a minuteDriver Scan →A request segment has no equals sign
Cause: The input is malformed, was truncated, or is not actually a Cookie header value. Fix: Record or reject the segment under an explicit policy and inspect the raw request at a safe diagnostic point. Do not silently fabricate a value.
Quick Recap
Implementation checklist
- Separate request
Cookieparsing from responseSet-Cookieparsing. - Split pairs on semicolons and split each pair at its first equals sign.
- Trim only surrounding spaces and tabs; preserve pair order and duplicate names.
- Define behavior for absent headers, empty segments, malformed pairs, and empty names.
- Keep raw values and decode only according to a documented application contract.
- Avoid logging sensitive cookie values, and do not assume client-side JavaScript can see HttpOnly or Set-Cookie data.
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

