Maaz Zindani

Loading the index…

↑↓ move↵ openesc close4072 pages
Next.js and React

InvalidStateError when calling send() on a new WebSocket

ErrorUncaught InvalidStateError: Failed to execute 'send' on 'WebSocket': Still in CONNECTING state

Short answer

send() throws InvalidStateError when readyState is CONNECTING, which is the state right after new WebSocket(). Do not send until the socket is open. Send from the open event, or put messages in a small queue and flush it when open fires. Check readyState before every other send.

  • Applies to Current browsers (WHATWG WebSocket API)
  • Updated
  • By Maaz Zindani, Senior Software Engineer

Fix it fast

  1. 1Find out which cause you have

    Print the readyState right before the failing send. 0 means CONNECTING, 1 OPEN, 2 CLOSING, 3 CLOSED.

    console.log(socket.readyState, WebSocket.CONNECTING, WebSocket.OPEN);
  2. 2Match what you see, then jump to its fix

    1. 1The error appears on the first message after page load, and readyState is 0send() runs right after new WebSocket()Fix
    2. 2The error comes from a button handler, timer or another module, and only when it fires earlyOther code sends before the connection is readyFix

What does the error look like?

  • Uncaught InvalidStateError: Failed to execute 'send' on 'WebSocket': Still in CONNECTING state
  • DOMException InvalidStateError on socket.send()

Cause 1 of 2

send() runs right after new WebSocket()

1Check

A new socket starts with readyState 0 (CONNECTING), meaning it is created but not yet open. Any send on the next line runs in that state.

grep -n "new WebSocket" -A3 src/*.js

2Fix

Move the first send into an open listener.

const socket = new WebSocket("wss://example.com/socket");
socket.addEventListener("open", () => {
  socket.send("hello");
});

3Verify

Reload the page. The message is sent once and the console shows no error.

socket.addEventListener('open', () => console.log('open', socket.readyState));

Confirmed by developer.mozilla.org

Did this fix it?

Cause 2 of 2

Other code sends before the connection is ready

1Check

Find every send call outside the open handler. Any of them can run while readyState is 0.

grep -rn "\.send(" src/

2Fix

Wrap send in a helper. When the socket is CONNECTING, wait for its open event once; when OPEN, send now. In the other states the data would be discarded, so handle that in your app.

function safeSend(socket, data) {
  if (socket.readyState === WebSocket.CONNECTING) {
    socket.addEventListener("open", () => socket.send(data), { once: true });
  } else if (socket.readyState === WebSocket.OPEN) {
    socket.send(data);
  }
}

3Verify

Click the button as early as possible after load. The message is delivered once the socket opens.

safeSend(socket, JSON.stringify({ type: 'ping' }));

Confirmed by developer.mozilla.org

Did this fix it?

How do I stop it coming back?

  • Funnel every send through one helper that checks readyState.
  • Disable the send button until the open event has fired.
  • Handle close and error events so you know when the socket is no longer usable.

Sources

How was this page made?

I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.

Related fixes

Web apps

tsconfig rejects allowImportingTsExtensions

An error that allowImportingTsExtensions needs noEmit or emitDeclarationOnly

allowImportingTsExtensions lets files import each other with .ts or .tsx extensions, and TypeScript only allows it together with noEmit or emitDeclarationOnly.

2 causes, each with a fix

Web apps

A POST to a Google Apps Script web app returns 405 or a CORS error

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Apps Script web apps run doPost for POST and doGet for GET, and the Apps Script guides describe no other entry points.

3 causes, each with a fix

Next step

Want this handled for good?

I look after servers, apps and releases end to end. Tell me what keeps breaking.