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:

How State Transitions Trigger Lifecycle Events

JavaScript relies on event listeners that map directly to state transitions within the readyState lifecycle:

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.