How to Fix Repeated Socket Connections in Socket.io


I recently ran into a Socket.io bug where my io.on('connection') handler was being consistently being triggered over and over again.

let count = 0;
io.on('connection', socket => console.log(`New Connection ${++count}`));

This would output the following.

New Connection 1
New Connection 2
New Connection 3
New Connection 4
New Connection 5
...

I kept troubleshooting my client code and found no issues.

Apparently, I had updated the socket.io-client package in my client application but not the socket.io package in my Express server.

socket.io-client and socket.io must be the same version.

If they are not, the sockets may fail to connect properly, which will force another attempt to reconnect, which will fail, and so on.

If you’d like, check out how to update all the dependencies in your package.json.