InvalidStateError when calling send() on a new WebSocket
Uncaught InvalidStateError: Failed to execute 'send' on 'WebSocket': Still in CONNECTING stateShort 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.
Fix it fast
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);2Match what you see, then jump to its fix
What does the error look like?
Uncaught InvalidStateError: Failed to execute 'send' on 'WebSocket': Still in CONNECTING stateDOMException 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/*.js2Fix
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
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
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 fixWeb apps
AuthUserPoolException: Auth UserPool not configured in a Next.js app
Auth UserPool not configured
The error means an Amplify Auth call ran before Amplify.configure did.
3 causes, each with a fixWeb apps
Module not found for antd/dist/antd.less after upgrading to Ant Design 5
Module not found: Error: Can't resolve 'antd/dist/antd.less'
Ant Design 5 dropped Less and the bundled CSS file for CSS-in-JS, so antd/dist/antd.less no longer exists.
3 causes, each with a fixWeb apps
Apollo Server rejects a request as a potential CSRF
HTTP 400 Bad Request from the GraphQL endpoint
Apollo Server's CSRF prevention is on by default.
3 causes, each with a fixWeb apps
Apollo Client is blocked by CORS when the GraphQL server runs on AWS Lambda
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Apollo Server does not set CORS for you when it runs behind a framework or integration, and on Lambda that layer is API Gateway.
5 causes, each with a fixWeb 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