socket.io-client
semver
>=4.0.0postconditions9functions5last verified2026-04-20coverage score100%Postconditions — what we check
- io · connect-error-eventerrorWhenconnection failsThrows
emits 'connect_error' eventRequired handlingCaller MUST attach connect_error event listener to handle connection failures. Without error handling: - Applications crash with uncaught exceptions (Node.js) - Silent failures confuse users (browser) - Stale data displayed without indication - Operations attempted while disconnected socket.active attribute indicates whether automatic reconnection will occur: - socket.active = true: Temporary failure, auto-reconnect enabled - socket.active = false: Server rejected (auth failure), manual reconnect requiredcostmediumin prodimmediate exceptionusers seeservice unavailablevisibilityvisibleSources[1] - io · disconnect-eventwarningWhensocket disconnectsThrows
emits 'disconnect' event with reasonRequired handlingCaller SHOULD attach disconnect event listener to handle unexpected disconnections. Without disconnect handling: - User unaware of connection loss - Application shows stale data - Operations continue while offline - Confusing user experience Disconnect reasons and auto-reconnect behavior: - 'io server disconnect': Server closed connection (NO auto-reconnect) - 'io client disconnect': socket.disconnect() called (NO auto-reconnect) - 'ping timeout': Heartbeat timeout (auto-reconnects) - 'transport close': Connection unexpectedly closed (auto-reconnects) - 'transport error': Connection error (auto-reconnects)costmediumin prodimmediate exceptionusers seeservice unavailablevisibilityvisibleSources[2] - io · parser-error-eventwarningWhenparser encounters malformed packetThrows
may emit 'error' event or enter limbo stateRequired handlingCaller SHOULD attach error event listener to handle parser/transport errors. Known issue (GitHub #1551): - Parser errors may not fire any event - Connection can enter limbo state - Particularly problematic with binary data - No way to recover without page reload Workaround: socket.io.on('error', handler) may catch some errorscostmediumin prodimmediate exceptionusers seeservice unavailablevisibilityvisibleSources[3] - emit · acknowledgement-timeoutinfoWhenserver does not acknowledge within timeoutReturnscallback invoked with timeout errorRequired handlingCaller SHOULD use .timeout() modifier when emitting events that expect acknowledgements. Without timeout: - Infinite loading states if server never responds - Callback never called - Poor user experience - No error feedback Usage: socket.timeout(5000).emit('event', data, (err, response) => { ... }) Promise-based: await socket.timeout(10000).emitWithAck('event', data)costmediumin prodimmediate exceptionusers seeservice unavailablevisibilityvisibleSources[1]
- emitWithAck · emit-with-ack-timeout-errorerrorWhenserver does not acknowledge within timeout set via .timeout(ms)Throws
Promise rejects with Error('operation has timed out')Required handlingCaller MUST wrap socket.timeout(ms).emitWithAck() in try-catch. Without timeout error handling: - Unhandled Promise rejection crashes Node.js (v15+) - Silent hang in browser applications - Loading spinners never resolve - UI state left in permanent "pending" state The exact error message from source is "operation has timed out". Note: emitWithAck() without .timeout() returns a Promise that NEVER rejects on timeout — the callback is simply never called. Always use .timeout() with emitWithAck() to get a rejecting Promise. Usage: try { const response = await socket.timeout(5000).emitWithAck('get-data', { id: 123 }); } catch (err) { if (err.message === 'operation has timed out') { // server did not respond within 5 seconds } }costmediumin prodimmediate exceptionusers seeservice unavailablevisibilityvisibleSources[4] - emitWithAck · emit-with-ack-disconnect-errorerrorWhensocket disconnects while waiting for server acknowledgementThrows
Promise rejects with Error('socket has been disconnected')Required handlingCaller MUST handle the case where the socket disconnects while awaiting an acknowledgement. This happens when: - Network drops between emit and acknowledgement - Server crashes before responding - Socket manually disconnected while request is in-flight Without disconnect error handling: - Unhandled Promise rejection - Data may have been sent to server (partial operation) - Client has no way to know if server processed the request Idempotent operations: Safe to retry on reconnection. Non-idempotent operations: MUST check server state before retrying to avoid duplicate processing (e.g., creating duplicate records). Usage: try { const response = await socket.timeout(5000).emitWithAck('create-order', data); } catch (err) { if (err.message === 'socket has been disconnected') { // check if order was created before retrying } }costhighin prodsilent failureusers seelost datavisibilitysilentSources[4] - emitWithAck · emit-with-ack-reserved-event-nameerrorWhenevent name matches a reserved Socket.IO event (connect, connect_error, disconnect, disconnecting)Throws
throws synchronously with Error('"<name>" is a reserved event name')Required handlingCaller MUST NOT emit events named: connect, connect_error, disconnect, disconnecting, newListener, removeListener. This throws synchronously (not as a rejected Promise), so it bypasses try-catch around the await expression. The throw happens during the emit call itself, before the Promise is created. This is a programming error, not a runtime condition — it indicates the event name must be changed at design time.costlowin prodimmediate exceptionusers seeservice unavailablevisibilityvisibleSources[5] - socket.io.reconnect_failed · reconnect-failed-eventwarningWhenall reconnection attempts exhausted (reconnectionAttempts limit reached)Throws
emits 'reconnect_failed' event on socket.io (the Manager)Required handlingCaller SHOULD listen for socket.io.on('reconnect_failed', handler) when using a finite reconnectionAttempts value. Without reconnect_failed handling: - Application silently stops working - No user-visible indication of permanent disconnection - UI remains in "reconnecting" state forever - Background jobs that depend on the socket queue without limit Default behavior: reconnectionAttempts = Infinity, so reconnect_failed never fires by default. Only fires when reconnectionAttempts is a finite number. Usage: const socket = io('http://localhost:3000', { reconnectionAttempts: 5 }); socket.io.on('reconnect_failed', () => { // All 5 attempts failed — show error, switch to fallback showPermanentDisconnectionError(); });costmediumin prodsilent failureusers seeservice unavailablevisibilitysilentSources[6] - socket.io.reconnect_error · reconnect-error-eventinfoWhenindividual reconnection attempt failsThrows
emits 'reconnect_error' event on socket.io (the Manager) with the Error from the failed attemptRequired handlingCaller SHOULD listen for socket.io.on('reconnect_error', handler) to observe per-attempt reconnection failures. This is distinct from 'reconnect_failed': - reconnect_error: fires on EACH failed attempt (Error included), reconnect continues - reconnect_failed: fires once when ALL attempts exhausted, reconnect stops Without reconnect_error handling: - No observability into why reconnection is failing - Cannot implement progressive error escalation (e.g., alert after 3 failures) - Cannot distinguish network errors from auth errors during reconnection - Cannot adjust reconnection strategy based on error type Typical use cases: - Logging: Record each failure for monitoring/alerting pipelines - Escalation: Show degraded-mode UI after N consecutive failures - Auth refresh: Detect auth errors and refresh tokens before next attempt Usage: const socket = io('http://localhost:3000', { reconnectionAttempts: 5 }); socket.io.on('reconnect_error', (error) => { console.error('Reconnection attempt failed:', error.message); // Track consecutive failures for escalation }); socket.io.on('reconnect_failed', () => { // All attempts exhausted — take action });costlowin prodsilent failureusers seeservice unavailablevisibilitysilentSources[7]
Sources
Every postcondition cites at least one of these. Numbered to match the footnotes above.
- [1]socket.io/docs/v4https://socket.io/docs/v4/client-api/
- [2]socket.io/docs/v4https://socket.io/docs/v4/client-socket-instance/
- [3]github.com/socketio/socket.io-clienthttps://github.com/socketio/socket.io-client/issues/1551
- [4]socket.io/docs/v4https://socket.io/docs/v4/client-api/#socketemitwithackeventname-args
- [5]socket.io/docs/v4https://socket.io/docs/v4/client-api/#event-connect
- [6]socket.io/docs/v4https://socket.io/docs/v4/client-api/#event-reconnect_failed
- [7]socket.io/docs/v4https://socket.io/docs/v4/client-api/#event-reconnect_error
Need a different package?
Request a profile