Script Valley
WebSockets & Real-Time Applications
How WebSockets Actually WorkLesson 1.4

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:

  • 0 CONNECTING โ€” handshake in progress.

  • 1 OPEN โ€” connection established, you can send.

  • 2 CLOSING โ€” close handshake initiated, waiting for server acknowledgment.

  • 3 CLOSED โ€” 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.

Up next

How to inspect WebSocket traffic in Chrome DevTools

Sign in to track progress

WebSocket readyState and connection lifecycle โ€” How WebSockets Actually Work โ€” WebSockets & Real-Time Applications โ€” Script Valley โ€” Script Valley