I'm trying to add a proxy to my react app for socket.io-client
I'm using setupProxy.js with http-proxy-middleware which works fine for APIs but not for sockets
Server code with node js
var app = require('express')();
var http = require('http').createServer(app);
var io = require('socket.io')(http);
app.get('/', function (req, res) {
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function (socket) {
setInterval(() => {
console.log('emit event');
io.emit('event', { data: 'worked successfully!' });
}, 1000);
});
http.listen(8080, function () {
console.log('listening on *:8080');
});
Client code with react
function App() {
const socket = socketIOClient('/', {
transports: ['websocket'],
});
useEffect(() => {
socket.on('connect', () => {
console.log('connected');
});
socket.on('event', (data) => {
console.log(data);
});
}, []);
return (
<div className='App'>
Socket Proxy test
</div>
);
}
and my setupProxy.js
const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = (app) => {
app.use(
'/socket.io',
createProxyMiddleware({
target: 'http://localhost:8080',
changeOrigin: true,
ws: true, // enable websocket proxy
logLevel: 'debug',
})
);
};