Skip to content

Commit

Permalink
fix: parse "Set-Cookie" response header with commas correctly (#2075)
Browse files Browse the repository at this point in the history
Co-authored-by: ushiboy <ushiboy.dev@gmail.com>
  • Loading branch information
ushiboy and ushiboy committed Mar 15, 2024
1 parent ec76862 commit 23c16e6
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 4 deletions.
12 changes: 8 additions & 4 deletions src/core/utils/HttpResponse/decorators.ts
@@ -1,5 +1,6 @@
import statuses from '@bundled-es-modules/statuses'
import type { HttpResponseInit } from '../../HttpResponse'
import { Headers as HeadersPolyfill } from 'headers-polyfill'

const { message } = statuses

Expand Down Expand Up @@ -40,10 +41,13 @@ export function decorateResponse(
// Cookie forwarding is only relevant in the browser.
if (typeof document !== 'undefined') {
// Write the mocked response cookies to the document.
// Note that Fetch API Headers will concatenate multiple "Set-Cookie"
// headers into a single comma-separated string, just as it does
// with any other multi-value headers.
const responseCookies = init.headers.get('Set-Cookie')?.split(',') || []
// Use `headers-polyfill` to get the Set-Cookie header value correctly.
// This is an alternative until TypeScript 5.2
// and Node.js v20 become the minimum supported version
// and getSetCookie in Headers can be used directly.
const responseCookies = HeadersPolyfill.prototype.getSetCookie.call(
init.headers,
)

for (const cookieString of responseCookies) {
// No need to parse the cookie headers because it's defined
Expand Down
1 change: 1 addition & 0 deletions test/browser/rest-api/cookies.mocks.ts
Expand Up @@ -23,6 +23,7 @@ const worker = setupWorker(
headers: [
['Set-Cookie', 'firstCookie=yes'],
['Set-Cookie', 'secondCookie=no; Max-Age=1000'],
['Set-Cookie', 'thirdCookie=1,2,3'],
],
},
)
Expand Down
1 change: 1 addition & 0 deletions test/browser/rest-api/cookies.test.ts
Expand Up @@ -48,5 +48,6 @@ test('allows setting multiple response cookies', async ({
expect(allCookies).toEqual({
firstCookie: 'yes',
secondCookie: 'no',
thirdCookie: '1,2,3',
})
})

0 comments on commit 23c16e6

Please sign in to comment.