LOGOMock Service Worker
  1. Recipes
  2. Cookies

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'
2
3const worker = setupWorker(
4 rest.post('/login', (req, res, ctx) => {
5 // Access the request's cookies.
6 const { authToken } = req.cookies
7
8 if (isValidToken(authToken)) {
9 return res(
10 ctx.json({
11 id: 'abc-123',
12 firstName: 'John',
13 }),
14 )
15 }
16
17 return res(
18 ctx.status(403),
19 ctx.json({ message: 'Failed to authenticate!' }),
20 )
21 }),
22)
23
24worker.start()
The value of req.cookies respects the req.credentials. Learn more about the Request Credentials.

Mock response cookies

1import { setupWorker, rest } from 'msw'
2
3const worker = setupWorker(
4 rest.post('/login', (req, res, ctx) => {
5 return res(
6 // Calling `ctx.cookie()` sets given cookies
7 // on `document.cookie` directly.
8 ctx.cookie('auth-token', 'abc-123'),
9 )
10 }),
11)
12
13worker.start()

Note that you still won't be able to access the Set-Cookie header on the response, as the cookie is set on the document directly, bypassing network.