Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Parse an HTTP Cookie header as semicolon-separated name-value pairs, splitting each pair at its first equals sign. Preserve duplicate names and raw values. Decode percent-encoding, Base64, JSON, or other formats only when the application that created the cookie documents that representation.

This distinction matters because Cookie and Set-Cookie are different headers. A request’s Cookie header contains values only; attributes such as Path, Domain, Expires, HttpOnly, Secure, and SameSite are supplied by Set-Cookie and are not recoverable from the request header. See RFC 6265 and the MDN Cookie reference.

What a Cookie header contains

RFC 6265 defines the request grammar as Cookie: name=value; name2=value2. After removing the field name, the remaining cookie string is a sequence of cookie pairs separated by a semicolon and optional space:

session=abc123; theme=dark; prefs=lang%3Den

Each segment normally has a name, an equals sign, and a value. The value can itself contain equals signs, so a parser must split at the first equals sign only. An absent or empty header represents an empty collection; a user agent may also choose not to send cookies because of policy or privacy settings.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.

Why duplicate names must survive parsing

Browsers can send same-name cookies created for different paths or domains. The request header does not include the metadata needed to distinguish them. Keep an ordered list of pairs, or map each name to a list, rather than silently overwriting one value with another or assuming the last value wins.

A robust parsing algorithm

  1. Remove the Cookie: field name if you received the complete header line.
  2. If the remaining string is empty, return an empty collection.
  3. Split on semicolons.
  4. Trim surrounding spaces and tabs from every segment.
  5. Find the first =. Text before it is the name; text after it is the value.
  6. Trim optional surrounding spaces and tabs from the name and value.
  7. For a segment without an equals sign, apply your documented malformed-input policy: reject it, report it, or skip it. Do not invent a value.
  8. Append the pair in input order, preserving duplicates and the original value for later verification.

Language-neutral pseudocode:

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

JavaScript: parse without corrupting values

This Node.js example returns an array, reports malformed segments, and keeps both the raw and optionally decoded value. It deliberately does not decode automatically.

function parseCookieHeader(header, { onMalformed = "skip" } = {}) {
  if (header == null || header === "") return [];
  const value = header.replace(/^Cookie:s*/i, "");
  const result = [];

  for (const part of value.split(";")) {
    const segment = part.trim();
    if (!segment) continue;
    const equals = segment.indexOf("=");
    if (equals < 0) {
      if (onMalformed === "throw") {
        throw new Error(`Malformed cookie segment: ${segment}`);
      }
      if (onMalformed === "report") result.push({ malformed: segment });
      continue;
    }
    const name = segment.slice(0, equals).trim();
    const rawValue = segment.slice(equals + 1).trim();
    result.push({ name, rawValue });
  }
  return result;
}

function decodePercentOnce(rawValue) {
  // Use only when the producer specifies percent-encoding.
  return decodeURIComponent(rawValue);
}

const header = "session=a=b=c; theme=dark; session=other";
console.log(parseCookieHeader(header));
// [ { name: 'session', rawValue: 'a=b=c' },
//   { name: 'theme', rawValue: 'dark' },
//   { name: 'session', rawValue: 'other' } ]

decodeURIComponent throws on malformed escape sequences. Catch that error at an application boundary and decide whether to reject the request or retain the raw value; do not silently replace invalid bytes with a different credential.

Python: an ordered, duplicate-preserving parser

from urllib.parse import unquote


def parse_cookie_header(header: str | None, malformed="skip"):
    if not header:
        return []
    if header.lower().startswith("cookie:"):
        header = header.split(":", 1)[1].lstrip()

    pairs = []
    for segment in header.split(";"):
        segment = segment.strip(" t")
        if not segment:
            continue
        if "=" not in segment:
            if malformed == "raise":
                raise ValueError(f"Malformed cookie segment: {segment!r}")
            if malformed == "report":
                pairs.append({"malformed": segment})
            continue
        name, raw_value = segment.split("=", 1)
        pairs.append({
            "name": name.strip(" t"),
            "raw_value": raw_value.strip(" t"),
        })
    return pairs

header = "session=a=b=c; theme=dark; session=other"
parsed = parse_cookie_header(header)
print(parsed)

# Only if the application contract says the value is URL-encoded:
for pair in parsed:
    if "raw_value" in pair:
        pair["decoded_value"] = unquote(pair["raw_value"])

For security-sensitive values, verify a signature against the documented representation. Keep the raw value available because decoding can change the bytes that were signed.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #2
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.

Decoding cookie values safely

RFC 6265 states that the semantics of cookie-value are not defined by the specification. It recommends encoding arbitrary data, such as with Base64, for compatibility, but it does not prescribe one universal encoding. Percent-encoding is common and MDN notes that it is not required by the RFC.

Percent-decoding

Apply percent-decoding only when the producer documents URL encoding or the application’s observed contract establishes it. Decode once, not repeatedly. A value such as prefs=lang%3Den can become lang=en; an opaque session identifier should normally remain opaque.

Base64, JSON, and encryption

Do not automatically Base64-decode, JSON-decode, decrypt, or parse every cookie. First identify the application’s format and keying rules. A Base64 string may contain signed data; JSON may be merely serialized text; an encrypted value cannot be interpreted without the correct algorithm and key. Treat unknown values as uninterpreted strings.

Malformed escapes and Unicode

Choose a strict policy for malformed escape sequences. Rejecting them is safer for authentication boundaries; retaining the raw value can be useful for diagnostics. Define whether your API works with text or raw bytes, and normalize neither unless the application explicitly requires it.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.

Cookie versus Set-Cookie

Header Direction Contents Correct parser
Set-Cookie Response to user agent One cookie pair followed by attributes such as Path, Domain, Expires, Max-Age, Secure, HttpOnly, SameSite, or Partitioned A Set-Cookie parser that understands attributes and dates
Cookie Request to origin server Semicolon-separated name-value pairs only The first-equals parser shown here

Do not feed a Set-Cookie string to the request parser. Commas can occur in an Expires date, and each response Set-Cookie field represents a separate cookie. Folding multiple fields into one comma-separated line can change semantics. The MDN Set-Cookie reference documents the attributes and the distinction.

What browsers expose—and what they hide

Server-side request handling

On a server, read the framework’s raw request-header value and apply a parser that preserves duplicates. Framework convenience maps may choose one value for a repeated name, so use the raw header when order or duplicates matter.

Frontend JavaScript

document.cookie exposes a semicolon-separated string for cookies available to the current document, but it does not expose HttpOnly cookies. Frontend code cannot read the Set-Cookie response header: Fetch filters it as a forbidden response-header name. Browser privacy settings, cookie policy, domain/path scope, and other restrictions can also result in no Cookie header being sent. See MDN document.cookie.

Testing and comparison checklist

  • Test an empty header and a header with leading or trailing whitespace.
  • Test values containing additional equals signs, such as token=a=b.
  • Test duplicate names and confirm that input order is retained.
  • Test percent-encoded, unencoded, and malformed escape sequences separately.
  • Test an empty value, such as flag=.
  • Decide how to handle a segment without an equals sign and document that policy.
  • Confirm whether your API exposes raw bytes, Unicode text, or both.
  • Keep parsing syntax separate from decoding, signature verification, and application deserialization.

When evaluating a third-party parser, compare RFC tolerance versus strict rejection, duplicate and ordering behavior, first-equals handling, whitespace and malformed-segment rules, automatic versus explicit percent-decoding, raw-byte support, and whether Set-Cookie attributes are exposed through a separate API.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Troubleshooting common failures

“My value was cut off at an equals sign”

The implementation probably used an unrestricted split. Use the index of the first equals sign or a split-with-limit operation.

“Only one duplicate cookie remains”

A dictionary assignment overwrote an earlier pair. Return an array, or map names to arrays, and remember that the request header cannot tell you which path or domain produced each duplicate.

“Path, Domain, or HttpOnly is missing”

Those are Set-Cookie attributes. They are not transmitted in the request’s Cookie header, so they cannot be reconstructed from it.

“URL decoding broke authentication”

The value may not be URL-encoded, or decoding may have changed signed bytes. Verify the producer’s contract, retain the raw value, and decode exactly once only where required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.

“The browser sends no cookies”

An empty header can be normal. Check domain and path scope, user-agent privacy settings, consent state, and whether the cookie is HttpOnly (which hides it from JavaScript). A frontend cannot use Set-Cookie as a readable response header.

“My Set-Cookie parser fails on Expires”

Use a parser designed for Set-Cookie. Its date can contain commas, and multiple fields must not be collapsed into one comma-separated value.

Or skip the browser setup

If your goal is to inspect a page before processing its cookies or to automate a clean capture, ScreenshotNeo provides a website screenshot API and MCP server. A single request returns PNG, JPEG, WebP, or PDF. It accepts cookie and consent banners like a visitor and removes more than 60 known consent platforms, newsletter popups, and chat widgets before capture; each cleanup step can be disabled. Only clean shots are billed: bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are free, and the response identifies the result with X-Page-Verdict and X-Billed headers. Its MCP tools—take_screenshot, get_page_info, and capture_pdf—work with Claude, Cursor, and other MCP clients.

cURL (see the ScreenshotNeo documentation):

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

Python:

import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)

Node.js:

const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

The Free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000 shots. Sign up free.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Frequently Asked Questions

Can I parse cookies with a regular expression?

A small split-and-first-equals parser is easier to audit and preserves values containing equals signs. Use a dedicated Set-Cookie parser for response attributes.

Does a Cookie header reveal whether a cookie is Secure?

No. Secure, HttpOnly, SameSite, Path, Domain, and expiry metadata belong to Set-Cookie and are absent from Cookie.

Should cookie names be URL-decoded?

Only if the application explicitly defines encoded names. Parsing should preserve the transmitted name and value; decoding is a separate, documented step.

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.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.