Is there an option to use MSW as a proxy? #887
-
I want to have an option to proxy all requests from The wanted API could be an object handler like this
I've tried really hard to find in the docs but couldn't find any solution, whereas reading this article makes me think this's doable. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 6 replies
-
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(proxy.headers),
ctx.body(await proxy.text())
)
})
]
const worker = setupWorker(...handlers)
worker.start()
Feel free to create a reproduction repository if you find this suggestion not working as expected. |
Beta Was this translation helpful? Give feedback.
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.