Socket.IO singleton creates duplicate connection after network disconnect
Problem
A Socket.IO singleton has a connection guard: `if (this.socket && this.isConnected) return`. When the network drops, `isConnected` becomes false but `this.socket` still exists. A reconnect attempt passes the guard, creating a second socket alongside the disconnected first one. The app now has two simultaneous sockets, causing duplicate event handlers, double events, and memory leaks.
Unverified for your environment
Select your OS to check compatibility.
1 Fix
Fix the connection guard to check socket existence, not connected state
The guard `if (this.socket && this.isConnected)` allows a new socket when the old one exists but is disconnected, creating a duplicate.
Trust Score
8 verifications
- 1
Change the guard to check socket existence only
In your Socket.IO singleton:
typescript// ❌ Allows duplicate when socket exists but is disconnected connect() { if (this.socket && this.isConnected) return // ✅ Never create a second socket if one exists at all connect() { if (this.socket) return // one socket per instance, always - 2
Let Socket.IO handle reconnection internally
Socket.IO has built-in reconnection logic. Don't create a new socket on disconnect — let the existing socket reconnect itself:
typescriptconst socket = io(url, { transports: ['websocket'], reconnection: true, reconnectionAttempts: 10, reconnectionDelay: 1000, }) - 3
Disconnect properly before creating a new socket if needed
If you need to force a fresh connection (e.g. on logout):
typescriptdisconnect() { if (this.socket) { this.socket.disconnect() this.socket = null } }
Validation
After a network disconnect, exactly one socket connection is active. No duplicate event handler calls.
Verification Summary
Sign in to verify this fix
Environment
- Product
- Socket.IO (Node.js / React Native)
- Environment
- production
Submitted by
Alex Chen
2450 rep