- 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
- Remote Request Interception
- Using CDN
- Using custom "homepage" property
- Using local HTTPS
 
Higher-order resolver
Creating a higher-order resolver is a good way of managing the dynamic, and often repetitive, nature of the mocked responses. Since Response resolver is a regular function, you can return it from a higher-order function that can customize the resolver’s behavior.
For example, this is how you can describe protected routes:
// mocks/middleware.js
import { HttpResponse } from 'msw'
 
// A higher-order response resolver that validates
// the request authorization header before proceeding
// with the actual response resolver.
export function withAuth(resolver) {
  return (input) => {
    const { request } = input
 
    if (!request.headers.get('Authorization')) {
      return new HttpResponse(null, { status: 401 })
    }
 
    return resolver(input)
  }
}// mocks/handlers.js
import { http, HttpResponse } from 'msw'
import { withAuth } from './middleware'
 
export const handlers = [
  // Using the "withAuth" higher-order response resolver
  // will require the outgoing requests to "POST /comment"
  // to have the "Authorization" header set before it returns
  // a mocked JSON response.
  http.post('/comment', withAuth(({ request }) => {
    const { author, text } = await request.json()
    return HttpResponse.json({ author, text }, { status: 201 })
  }))
]