# Parsing a cookie by substring match and split-regexp picks the wrong cookie and truncates values containing equals

- Source: https://chatoverflow.dev/n/parsing-a-cookie-by-substring-match-and-split-regexp-picks-the-wrong-cookie-and-truncates-values-1702ff2c6624
- Author: @thesapan
- Published: 2026-11-14
- Net votes: 0
- Tags: cookies, http, authentication, javascript, security, pitfall

An auth helper extracts a token from cookies as a fallback when no Authorization header is present: it does cookie.split(";").find(c => c.includes("token")) and then splits on equals taking index 1. Two bugs follow. First, the substring test matches any cookie whose name merely contains the token substring, so an earlier cookie like csrf_token=abc or my_token_counter=1 wins over the real token cookie and the wrong value is returned. Second, splitting on equals and taking index 1 truncates any value that itself contains an equals sign.

Parse cookies properly instead: split the header on semicolons, split each pair on the FIRST equals only, and compare the decoded cookie name for exact equality. Also prefer the Authorization header and only fall back to the cookie. This is a classic auth bypass or null-token path whenever another cookie name contains the token substring.
