Understanding WebSocket readyState in JavaScript
The WebSocket readyState property is a read-only
attribute that reports the real-time status of a WebSocket connection
directly to JavaScript. As a connection moves through its lifecycle—from
the initial handshake to termination—readyState updates
with predefined numeric constants (0 through 3) representing four
distinct phases: CONNECTING, OPEN,
CLOSING, and CLOSED. By evaluating this
property alongside lifecycle event listeners, developers can monitor
connection health, prevent runtime errors, and safely transmit data
across the network.
The Four Connection States
The WebSocket API defines four constants on the
WebSocket interface to represent the connection
lifecycle:
0—WebSocket.CONNECTING: The connection has been initiated, but the underlying TCP connection and WebSocket upgrade handshake have not yet completed. Any attempt to send data viasocket.send()in this state will throw anINVALID_STATE_ERR.1—WebSocket.OPEN: The handshake was successful, and the connection is active. The client and server can now exchange messages bidirectionally via full-duplex communication.2—WebSocket.CLOSING: The connection is executing a closing handshake. This state is triggered when either the client invokessocket.close()or the server sends a close frame. Data cannot be sent while in this state.3—WebSocket.CLOSED: The connection is completely terminated or failed to establish. Once in this state, the WebSocket instance cannot be reopened; a new instance must be created to establish a new connection.
How State Transitions Trigger Lifecycle Events
JavaScript relies on event listeners that map directly to state
transitions within the readyState lifecycle:
openEvent: Fires whenreadyStatechanges from0(CONNECTING) to1(OPEN). This is the standard trigger to begin sending authentication payloads or initial data.messageEvent: Fires when incoming data is received whilereadyStateis1(OPEN).errorEvent: Fires when an issue prevents the connection from establishing or maintaining communication. Anerrorevent typically precedes a transition to state3.closeEvent: Fires whenreadyStatetransitions to3(CLOSED). The event object provides a close code and reason, indicating whether the termination was intentional or caused by a network interruption.
Monitoring readyState in Practice
While event listeners notify an application when state changes occur,
directly querying socket.readyState allows synchronous
verification before performing actions.
const socket = new WebSocket('wss://example.com/socket');
// Checking state before transmitting data
function sendMessage(data) {
if (socket.readyState === WebSocket.OPEN) {
socket.send(JSON.stringify(data));
} else if (socket.readyState === WebSocket.CONNECTING) {
console.warn('Connection is still initializing. Message queued or delayed.');
} else {
console.error('Cannot send message. Socket is closing or closed.');
}
}Evaluating socket.readyState prevents silent failures
and exceptions, ensuring that data is only transmitted when the
connection is fully established.