WebSocket readyState and connection lifecycle
CONNECTING state, OPEN state, CLOSING state, CLOSED state, onopen event, onclose event, onerror event, close codes, graceful shutdown
The Four States of a WebSocket
A WebSocket object always has a readyState property with one of four values:
0CONNECTING โ handshake in progress.1OPEN โ connection established, you can send.2CLOSING โ close handshake initiated, waiting for server acknowledgment.3CLOSED โ connection is dead.
Calling send() while readyState !== 1 throws an error. Always guard sends:
if (ws.readyState === WebSocket.OPEN) { ws.send(JSON.stringify({ type: 'message', text })); }
Handling the Close Event Correctly
The onclose event receives a CloseEvent with a numeric code and a reason string. Code 1000 is a normal closure. Code 1006 means the connection was lost abnormally โ no close frame was received (network drop, server crash). Use this to trigger reconnection logic:
ws.onclose = (event) => { if (event.code !== 1000) { scheduleReconnect(); } };
The onerror event fires before onclose on abnormal termination. It carries no useful detail beyond the fact that an error occurred; the close code is more informative. Do not show raw error events to users.
