Cookies
Limitations
Fetch specification explicitly forbids setting Set-Cookie
and Set-Cookie2
headers when constructing a new Response
instance for security reasons.
However, since Mock Service Worker executes on the client side, it can provide a functionality similar to receiving a mocked cookie from the response, without violating security. To achieve that, use the ctx.cookie()
response transformer function that sets the given cookies on the document.cookie
string directly.
Examples
Access request cookies
1import { setupWorker, rest } from 'msw'23const worker = setupWorker(4 rest.post('/login', (req, res, ctx) => {5 // Access the request's cookies.6 const { authToken } = req.cookies78 if (isValidToken(authToken)) {9 return res(10 ctx.json({11 id: 'abc-123',12 firstName: 'John',13 }),14 )15 }1617 return res(18 ctx.status(403),19 ctx.json({ message: 'Failed to authenticate!' }),20 )21 }),22)2324worker.start()
Mock response cookies
1import { setupWorker, rest } from 'msw'23const worker = setupWorker(4 rest.post('/login', (req, res, ctx) => {5 return res(6 // Calling `ctx.cookie()` sets given cookies7 // on `document.cookie` directly.8 ctx.cookie('auth-token', 'abc-123'),9 )10 }),11)1213worker.start()
Note that you still won't be able to access the
Set-Cookie
header on the response, as the cookie is set on thedocument
directly, bypassing network.