Handling requests

Different ways to handle an intercepted HTTP request.

This page will walk you through all the possible ways to handle an intercepted request in MSW. It is up to you to choose the right approach, or a combination of them, based on what you want to achieve in your mocks.

Respond with a mocked response

If you return a Response instance from the response resolver, that response will be used as the mocked response for the request. Please learn more about mocking responses on this page:

Mocking responses

Declaring and using mocked responses.

Passthrough

You can perform the intercepted request as-is and return its original response (i.e. passthrough a request) by returning the result of the passthrough() function call.

import { passthrough } from 'msw'
 
http.get('/resource', () => {
  return passthrough()
})

This is especially useful when you only want to mock a response in certain situations and perform the request as-is otherwise.

http.get('https://api.example.com/resource', async ({ request }) => {
  const data = await request.clone().json()
 
  if (data?.id === 'abc-123') {
    return HttpResponse.json({ id: 'abc-123' })
  }
 
  return passthrough()
})

Above, you can intercept a request, parse its body as JSON, and then decide whether you want to respond with a mock or perform it as-is.

Return nothing

You can also return nothing from the response resolver, either explicitly or implicitly. If that happens, MSW will continue to look for other request handlers that might match ths request. You can utilize this for network introspection or any other side effects that do not involve responding to the request.

export const handlers = [
  http.get('/resource', ({ request }) => {
    console.log('Request intercepted!', request.method, request.url)
  }),
  http.get('/resource', () => {
    return HttpResponse.text('hello world')
  }),
]

In this example, the first request handler will match, log the message to the console, and, since it returns nothing, finish. The second request hander will then match the same request and handle it with a mocked response, as an example.