Skip to content

feat: handle multiple Set-Cookie headers#108

Open
uncrft wants to merge 1 commit intovalendres:mainfrom
uncrft:handle-multiple-set-cookie-header
Open

feat: handle multiple Set-Cookie headers#108
uncrft wants to merge 1 commit intovalendres:mainfrom
uncrft:handle-multiple-set-cookie-header

Conversation

@uncrft
Copy link
Copy Markdown

@uncrft uncrft commented Jan 23, 2025

Context

msw allows setting cookies in mock handlers by setting the Set-Cookie header.

http.post("/api/login", () => {
  return new HttpResponse(null, { 
    headers: {
      "Set-Cookie": "token=my-token"
    }
  })
})

As long as a single Set-Cookie header is set, playwright-msw handles it perfectly. However, msw also accepts a Headers object. The spec allows storing multiple entries of the same header stored as comma-separated strings. These multi-entries headers can be constructed using append. It's such a common use-case that the spec includes a getSetCookie utility function to retrieve the array of Set-Cookie headers.

http.post('/api/login', () => {
  const headers = new Headers()
  headers.append("Set-Cookie", "accessToken=my-access-token")
  headers.append("Set-Cookie", "refreshToken=my-refresh-token")
  console.log(headers.get("Set-Cookie") // "accessToken=my-access-token, refreshToken=my-refresh-token"
  console.log(headers.getSetCookie()) // ["accessToken=my-access-token", "refreshToken=my-refresh-token"]
  return new HttpResponse(null, { headers })
})

And this is where the issue arises: Playwright's route.fulfill function expects a Record<string, string> for the headers, but it does not handle comma-separated values. The current implementation iterates over the header entries from the mocked response to create an object compliant with route.fulfill, as a consequence only the last entry of each header is accounted for.

Proposed solution

Playwright exposes the BrowserContext.addCookies function which could be used to set cookies instead of relying on route.fulfill. However the function does not handle cookie strings, but rather a parsed version. I implemented a parseSetCookieHeades function converting the mocked response headers into a BrowserContext.addCookies compliant object, and updated the onMockedResponse callback of msw's handleRequest function to handle Set-Cookie headers separately from the other headers.

@uncrft uncrft requested a review from valendres as a code owner January 23, 2025 17:45
@uncrft uncrft changed the title Handle multiple Set-Cookie headers feat: handle multiple Set-Cookie headers Jan 23, 2025
@Merlissa09 Merlissa09 self-assigned this Jul 26, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants