Description
Is your proposal related to a problem?
The documentation for Configuring the Proxy Manually provides an example on how to setup a proxy by using the express
server's app.use
path
parameter to match requests.
const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = function(app) {
app.use(
'/api',
createProxyMiddleware({
target: 'http://localhost:5000/',
changeOrigin: true,
})
);
};
The problem is that express
is configured for http/https and not ws/wss, so it doesn't work for proxying websocket connections. However, by providing the proxy path to http-proxy-middleware
createProxyMiddleware
instead, the websocket can be proxied just fine:
const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = function(app) {
app.use(createProxyMiddleware('/api', {
target: 'http://localhost:5000/',
changeOrigin: true,
})
);
};
Describe the solution you'd like
I would like to see the documentation for Configuring the Proxy Manually to be changed so that the proxy path is passed to createProxyMiddleware
rather than app.use
. As far as I am aware, this shouldn't be any different for http/https proxies, but should also work for ws/wss proxies.
Or, at the very least, add a section on creating proxies for websockets.
Describe alternatives you've considered
When I was working on this issue, I did try the External WebSocket upgrade solution provided by http-proxy-middleware
, and while it did proxy the websocket request correctly, I also kept receiving WebSocket connection to 'ws://localhost:3000/ws' failed
errors in my console. I think this has to do with webpack's hot reload feature, but I'm by no means an expert in this area.
Additional context
Normally I wouldn't bring up such a small issue, but truth be told I was stuck on this for a week. I'm not an expert in CRA, Webpack, or proxies, so I had to rely on a lot of online documentation to try and figure out how to get this to work. I did have a working example of a websocket proxy from our legacy React app that used the proxy()
function from http-proxy-middleware
, but it was created over 5 years ago and CRA had been ejected, so that solution wasn't working.
I got to the point of ejecting CRA to try and work out that solution, and it led me to this SO comment which showed me that I could just pass the path
parameter directly to createProxyMiddleware
instead of app.use
.
It was frustrating that the solution to my problem was that the path
parameter just needed to be shifted over to the next function. I'm hoping that updating the documentation will be able to save time for the next person.