- Introduction
- Getting started
- Philosophy
- Comparison
- Limitations
- Debugging runbook
- FAQ
- Basics
- Concepts
- Network behavior
- Integrations
- API
- CLI
- Best practices
- Recipes
- Cookies
- Query parameters
- Response patching
- Polling
- Streaming
- Network errors
- File uploads
- Responding with binary
- Custom worker script location
- Global response delay
- GraphQL query batching
- Higher-order resolver
- Keeping mocks in sync
- Merging Service Workers
- Mock GraphQL schema
- Using CDN
- Using custom "homepage" property
- Using local HTTPS
Cookies
Handle request and response cookies.
Read request cookies
You can access the intercepted request cookies using the cookies
argument of the response resolver:
import { http, HttpResponse } from 'msw'
export const handlers = [
http.get('/api/user', ({ cookies }) => {
if (!cookies.authToken) {
return new HttpResponse(null, { status: 403 })
}
return HttpResponse.json({ name: 'John' })
}),
]
Note that the value of
cookies
respects Request credentials, and may contain more data than originally sent in the request (e.g. when thecredentials
property of the request was set to"include"
).
Mock response cookies
Mocking response cookies is often challenging because the Fetch specification forbids setting Set-Cookie
and Set-Cookie2
headers on manually constructed responses for security reasons.
Since Mock Service Worker executes on the client, it can work around this limitation by setting mocked response cookies directly on the document.cookie
, as if they were received from the server. This approach doesn’t compromise response security while still allowing you to test your application’s cookie handling logic.
import { http, HttpResponse } from 'msw'
export const handlers = [
http.post('/login', () => {
return new HttpResponse(null, {
headers: {
// Setting the "Set-Cookie" mocked response header
// will forward these cookies onto "document" as if they
// were sent from the server.
'Set-Cookie': 'authToken=abc-123',
},
})
}),
]
Note that you must use the
HttpResponse
class in order to set mocked response cookies. This way MSW can detect response cookies because they cannot be accessed in JavaScript once set.