Skip to content

Commit c307ab2

Browse files
authoredSep 10, 2024··
fix: remove cookies with max-age=0 from cookie store (#2275)
1 parent 1263c0f commit c307ab2

File tree

2 files changed

+47
-1
lines changed

2 files changed

+47
-1
lines changed
 

‎src/core/utils/cookieStore.ts

+20
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,11 @@ class WebStorageCookieStore extends Store {
7575
callback: (error: Error | null) => void,
7676
): void {
7777
try {
78+
// Never set cookies with `maxAge` of `0`.
79+
if (cookie.maxAge === 0) {
80+
return
81+
}
82+
7883
const store = this.getStore()
7984
store.push(cookie)
8085
this.updateStore(store)
@@ -90,6 +95,21 @@ class WebStorageCookieStore extends Store {
9095
newCookie: CookieInstance,
9196
callback: (error: Error | null) => void,
9297
): void {
98+
/**
99+
* If updating a cookie with `maxAge` of `0`, remove it from the store.
100+
* Otherwise, two cookie entries will be created.
101+
* @see https://github.com/mswjs/msw/issues/2272
102+
*/
103+
if (newCookie.maxAge === 0) {
104+
this.removeCookie(
105+
newCookie.domain || '',
106+
newCookie.path || '',
107+
newCookie.key,
108+
callback,
109+
)
110+
return
111+
}
112+
93113
this.putCookie(newCookie, callback)
94114
}
95115

‎test/browser/rest-api/request/request-cookies.test.ts

+27-1
Original file line numberDiff line numberDiff line change
@@ -177,7 +177,6 @@ test('inherits mocked "HttpOnly" cookies', async ({
177177
test('respects cookie "Path" when exposing cookies', async ({
178178
loadExample,
179179
fetch,
180-
page,
181180
}) => {
182181
await loadExample(require.resolve('./request-cookies.mocks.ts'))
183182

@@ -203,3 +202,30 @@ test('respects cookie "Path" when exposing cookies', async ({
203202
mockedCookie: 'mockedValue',
204203
})
205204
})
205+
206+
test('deletes a cookie when sending "max-age=0" in a mocked response', async ({
207+
loadExample,
208+
fetch,
209+
}) => {
210+
await loadExample(require.resolve('./request-cookies.mocks.ts'))
211+
212+
// First, set the cookie.
213+
await fetch('/set-cookies', {
214+
method: 'POST',
215+
body: `mockedCookie=mockedValue`,
216+
})
217+
218+
// Must forward the mocked cookied to the matching request.
219+
await expect(fetch('/cookies').then((res) => res.json())).resolves.toEqual({
220+
mockedCookie: 'mockedValue',
221+
})
222+
223+
// Next, delete the cookie by setting "max-age=0".
224+
await fetch('/set-cookies', {
225+
method: 'POST',
226+
body: `mockedCookie=mockedValue; max-age=0`,
227+
})
228+
229+
// Must NOT have any cookies on the matching request.
230+
await expect(fetch('/cookies').then((res) => res.json())).resolves.toEqual({})
231+
})

0 commit comments

Comments
 (0)
Please sign in to comment.