Skip to content
Latchkey

ws "WebSocket is not open: readyState 3 (CLOSED)" in CI

The Node ws library throws "WebSocket is not open: readyState 3 (CLOSED)" when you call .send() after the socket has closed. readyState 3 is CLOSED; the write had nowhere to go.

What this error means

A test throws from ws.send(...) with this message. It flakes because the test sends before the open event, or after the server already closed the connection.

ws
Error: WebSocket is not open: readyState 3 (CLOSED)
    at WebSocket.send (node_modules/ws/lib/websocket.js:...)

Common causes

send() called before open or after close

The test writes to the socket while it is still connecting (readyState 0) and it later closes, or writes after the peer closed it (readyState 3).

The server closed the connection early

A rejected handshake or an unhandled error on the server closes the socket, and the client's next send hits a CLOSED state.

How to fix it

Send only after the open event

  1. Wait for open before the first send.
  2. Guard sends with a readyState === WebSocket.OPEN check.
  3. Handle the close and error events so failures are visible, not silent.
test.mjs
ws.on('open', () => ws.send('hello'));
ws.on('error', (e) => done(e));

Guard every send with readyState

Never call send blindly; check the socket is OPEN first.

test.mjs
if (ws.readyState === ws.OPEN) ws.send(payload);

How to prevent it

  • Await the open event before sending in tests.
  • Attach close/error handlers so an early close surfaces clearly.
  • Guard sends with an OPEN readyState check.

Frequently asked questions

What causes ""WebSocket is not open: readyState 3 (CLOSED)""?
The test writes to the socket while it is still connecting (readyState 0) and it later closes, or writes after the peer closed it (readyState 3).
How do I fix "WebSocket is not open: readyState 3 (CLOSED)"?
Send only after the open event

Related guides

References

Latchkey auto-heals failures like this one - detected, fixed, and retried without you. Start free → 30-day trial · No credit card