Is there an option to use MSW as a proxy? #887
Answered
by
kettanaito
loia5tqd001
asked this question in
Q&A
|
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. |
Answered by
kettanaito
Aug 26, 2021
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. |
6 replies
Answer selected by
loia5tqd001
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment

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.