Response patching

Combine original and mocked responses.

Response patching is a technique to combine a mocked response with the real response. This technique is particularly useful when working with existing API (including third-party API) as it allows to augment its responses on the fly.

To get the original response to the intercepted request you have to perform it as-is. If you use the plain fetch() function in the handler, it will dispatch a request that will again match the same handler, causing an infinite request loop. Instead, use the bypass() utility function that will mark any given Request instance as the one to be bypassed by any otherwise matching request handlers.

import { http, bypass, HttpResponse } from 'msw'
 
export const handlers = [
  http.get('https://api.github.com/user/:username', async ({ request }) => {
    // Fetch the original response from the GitHub API.
    const gitHubUser = await fetch(bypass(request)).then((response) =>
      response.json()
    )
 
    // Respond with a mocked response that combines
    // the actual and mock data.
    return HttpResponse.json({
      id: gitHubUser.id,
      login: gitHubUser.login,
      location: 'London',
    })
  }),
]

bypass

API reference for the `bypass` function.

Proxying requests

You can proxy outgoing requests by constructing a designed proxy Request instance.

import { http, bypass } from 'msw'
 
export const handlers = [
  http.get('/resource', async ({ request }) => {
    const originalUrl = new URL(request.url)
    const proxyUrl = new URL('/proxy', location.origin)
 
    // Construct a proxy request.
    const proxyRequest = new Request(proxyUrl, {
      headers: {
        'Content-Type': request.headers.get('Content-Type'),
        'X-Proxy-Header': 'true',
      },
    })
 
    // Perform the proxy request.
    const originalResponse = await fetch(bypass(proxyRequest))
 
    // Return the mocked response...
  }),
]