Created by: mirek
Currently when using custom proxy with src/setupProxy.js
there is no way to manually register protocol upgrade for target services providing websocket connections.
This means that if the first request to the proxy happens to be a websocket connection, the request will hang.
This PR adds backward compatible server
as 2nd parameter to proxy setup provided by the user. This allows to register protocol upgrade handler manually and avoid problems with first proxy request being websocket connection request.
Currently not pretty workarounds are required [1] or:
const http = require('http')
const { createProxyMiddleware } = require('http-proxy-middleware')
module.exports = function (app) {
app.use(
'/api',
createProxyMiddleware({
target: `http://localhost:${process.env.REACT_APP_MY_BACKEND_PORT}`,
changeOrigin: true,
ws: true,
pathRewrite: {
'^/api': ''
}
})
)
// HACK: http-proxy-middleware relies on a initial http request in order to listen to the http upgrade event.
const retry = () => {
setTimeout(() => {
http.get(`http://localhost:${process.env.PORT || 3000}/api/health-or-something-else`, res => {
const { statusCode } = res
if (statusCode !== 200) {
retry()
}
})
}, 1000)
}
retry()
}
With this patch applied, proxy setup can manually register protocol upgrade handler:
const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = function(app, server) {
const proxy = createProxyMiddleware({
target: 'http://localhost:5000',
changeOrigin: true,
ws: true
})
app.use('/api', proxy);
server.on('upgrade', proxy.upgrade);
};
[1] https://github.com/chimurai/http-proxy-middleware/issues/432