Skip to content
This repository has been archived by the owner on Jul 8, 2023. It is now read-only.

Commit

Permalink
Ensure consistent behavior for duplicate cookies
Browse files Browse the repository at this point in the history
In the case of two (or more) cookies with the same name visible to the
current scope, so far we've been retrieving the first one we find for
`getCookie()`, but the last one for `getCookies()` (because in the
latter case we continued the loop and eventually overwrote a duplicate
cookie name in the returned result/object).

This change makes the behavior at least consistent, so there aren't
different cookies in the result for both calls.

Changing the api to include both cookies in the result seems reasonable.

For context: js-cookie#813
  • Loading branch information
carhartl committed Jun 24, 2023
1 parent f80d5ab commit 4562361
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/api.ts
Expand Up @@ -64,7 +64,7 @@ function get<T extends string | undefined, U>(
while ((match = scan.exec(document.cookie)) != null) {
try {
const found = decodeName(match[1])
jar[found] = decodeValue(match[2], found)
if (!(found in jar)) jar[found] = decodeValue(match[2], found)
if (name === found) {
break
}
Expand Down
14 changes: 14 additions & 0 deletions test/api.test.ts
Expand Up @@ -214,6 +214,13 @@ describe('getCookie', () => {
document.cookie = 'invalid=foo; expires=Thu, 01 Jan 1970 00:00:00 GMT'
})

test('when there is a duplicate cookie', () => {
document.cookie = 'c=one; path=/'
document.cookie = 'c=two; path=/test'
expect(getCookie('c')).toBe('two') // 2nd (nested) cookie comes first...!
document.cookie = 'c=v; path=/test; expires=Thu, 01 Jan 1970 00:00:00 GMT'
})

describe('decode', () => {
test('with customized value decoding', () => {
document.cookie = 'c=v'
Expand Down Expand Up @@ -271,6 +278,13 @@ describe('getCookies', () => {
expect(getCookies()).toStrictEqual({})
})

test('when there are duplicate cookies', () => {
document.cookie = 'c=one; path=/'
document.cookie = 'c=two; path=/test'
expect(getCookies()).toStrictEqual({ c: 'two' }) // 2nd (nested) cookie comes first...!
document.cookie = 'c=v; path=/test; expires=Thu, 01 Jan 1970 00:00:00 GMT'
})

// github.com/js-cookie/js-cookie/issues/196
test('when there is a cookie with malformed encoding in the name', () => {
document.cookie = '%A1=foo'
Expand Down

0 comments on commit 4562361

Please sign in to comment.