Search code examples
cookiesjestjsfetchjsdommsw

How to make mock service worker running in node + jsdom (for tests) receive cross-domain cookies?


I've got a reproduction repo with Jest + MSW, and I'm trying get MSW to receive cross-domain cookies. By default, JSDOM loads on http://localhost. When sending fetch requests to this domain & MSW listens on this domain too, all is fine, the cookies are received.

However, when trying to send requests to another domain, like http://localhost:4444, no cookies are sent to MSW. What's weird is that if I comment out MSW and start an express server on that same port, it does indeed receive all the cookies. How come they're being sent to the express server but not to MSW?

Finally, what's also weird is that if both MSW and the express server are running, with MSW on 4444 and Express on 5555, the express server will no longer receive the cookies. It's as if MSW's beforeAll(() => server.listen()); is somehow killing the cross-domain cookies.

Cookies set:

setCookie("local00=L00", "http://localhost");
setCookie("local44=L44", "http://localhost:4444");
setCookie("local55=L55", "http://localhost:5555");
setCookie("local66=L66", "http://localhost:6666");
fetch(http://localhost)      --> handler("http://localhost"):     OK! all cookies received

fetch(http://localhost:4444) --> handler("http://localhost:4444): No cookies received
                             OR
                             --> express("http://localhost:4444): OK! all cookies received

fetch(http://localhost:4444) --> handler("http://localhost:5555): No cookies received
                             AND
                             --> express("http://localhost:4444): No cookies received

How can I send cross origin requests to MSW and have it receive cookies?


Solution

  • MSW does not currently support the credentials option on window.fetch when running in JSDOM (see the related issue, and the pull request that adds that support). Expect this feature added in the next minor version. Thanks.