set-cookie-parser icon indicating copy to clipboard operation
set-cookie-parser copied to clipboard

Incorrectly parsed cookie

Open LenweSaralonde opened this issue 2 months ago • 2 comments

I received these 2 cookies in a single line from a back end :

csrftoken=XXXXXXXX; expires=Fri, 11 Dec 2026 14:37:02 GMT; Max-Age=31449600; Path=/; SameSite=Strict; Secure, USER_SESSION_member_space=YYYYYYYY; expires=Sat, 13 Dec 2025 00:37:02 GMT; HttpOnly; Max-Age=36000; Path=/; SameSite=None; Secure

Result using parse method :

Parsed [
  [Object: null prototype] {
    name: 'csrftoken',
    value: 'XXXXXXXX',
    expires: 2025-12-13T00:37:02.000Z,
    maxAge: 36000,
    path: '/',
    sameSite: 'None',
    'secure, user_session_member_space': 'YYYYYYYY',
    httpOnly: true,
    secure: true
  }
]

Only the first cookie is parsed but with the expiration date of the second one.

I expect to have 2 cookies parsed with the correct expiration date.

Maybe this cookie string is not perfectly compliant but I tested it using this online tool https://rapidtoolset.com/en/tool/cookie-parser and I got correct results.

LenweSaralonde avatar Dec 12 '25 14:12 LenweSaralonde

Use the splitCookieString() method on it first, the pass the result of that to the regular parse() method. See https://github.com/nfriedly/set-cookie-parser?tab=readme-ov-file#usage-in-react-native-and-with-some-other-fetch-implementations for an example.

Combining all cookies into one string is allowed by the spec, but it's not very common because it's difficult to parse (because commas are used both in the cookies and as a separator). It's been on my todo list for a while to release a new version of the library that does this automatically when applicable, but I haven't done it yet because there are some other changes I want to include at the same time and I haven't figured out exactly what I want to do there. See https://github.com/nfriedly/set-cookie-parser/discussions/68 for more info.

nfriedly avatar Dec 12 '25 20:12 nfriedly

Use the splitCookieString() method on it first, the pass the result of that to the regular parse() method. See https://github.com/nfriedly/set-cookie-parser?tab=readme-ov-file#usage-in-react-native-and-with-some-other-fetch-implementations for an example.

OK, got you. I was expecting splitCookieString() to be used internally by parse() so we could provide either an array of single cookie strings or a a string containing one or multiple cookies.

Using splitCookieString() first fixes my problem, thank you.

Please consider this as an improvement suggestion, not a bug.

LenweSaralonde avatar Dec 15 '25 10:12 LenweSaralonde