Skip to content

Is there an option to use MSW as a proxy? #887

Answered by kettanaito
loia5tqd001 asked this question in Q&A
Discussion options

You must be logged in to vote

Hey, @loia5tqd001.

MSW is primarily designed for mocking. That being said, you can utilize its request capturing capabilities to capture a range of requests and proxy them to another endpoint.

import { setupWorker, rest, RESTMethods } from 'msw'

// Create a custom method to generate 
// the same request handler for all REST API methods.
function createProxy(url, resolver) {
  return Object.values(RESTMethods).map((method) => {
    return res[method](url, resolver)
  })
}

export const handlers = [
  // Capture all /api/*" requests and proxy them.
  createProxy('/api/*', (req, res, ctx) => {
    const proxy = await ctx.fetch(req)
    return res(
      ctx.status(proxy.status),
      ctx.set(

Replies: 1 comment 6 replies

Comment options

You must be logged in to vote
6 replies
@kettanaito
Comment options

@loia5tqd001
Comment options

@kettanaito
Comment options

@jcollum-nutrien
Comment options

@kettanaito
Comment options

Answer selected by loia5tqd001
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
3 participants
Converted from issue

This discussion was converted from issue #886 on August 26, 2021 12:33.