Quick answer: Queue outbound messages until onopen, gate sends on readyState, and centralize socket lifecycle in one wrapper that handles reconnects and flushes the queue.
A WebSocket is not usable at construction — it opens asynchronously. Racing it (or ignoring closure) throws this. A thin wrapper makes every call site safe. Here is its shape.
How to fix it
1. Send only after open
First packets belong in socket.onopen — construction-then-immediate-send works on localhost timing and fails on real latency.
2. Queue through a wrapper
A safeSend(msg) that buffers while CONNECTING and flushes on open (dropping or persisting on CLOSED per message type) removes the race from every caller.
3. Handle the disconnected state
Gameplay code sending into a closed socket throws the sibling error — the wrapper should transition to reconnect logic and either buffer critical messages or surface 'connection lost' UI.
4. Reconnect with backoff
On close, retry with exponential backoff and jitter, re-authenticate, then flush — and report repeated failures to your error tracking with the close code.
Catching the ones you can't reproduce
The hardest version of this to fix is the one you can't reproduce — it only happens on a player's hardware, OS, driver, or save state, under conditions that simply aren't present on your machine. A report that says “it crashed” or “it froze” gives you nothing to act on, so the bug survives release after release while quietly costing you players.
Automatic error capture closes that gap. Each failure arrives with its full stack trace, the device and OS, the build number, and a breadcrumb trail of what the player did right before it broke, so even a failure you have never seen becomes a specific, reproducible issue. Fold identical failures into one signature ranked by how many players each hits, and your worklist sorts itself worst-first instead of arriving as a stream of vague complaints.
This is where a tool like Bugnet earns its place. Its SDK captures every HTML5 error automatically with the full stack trace plus device, OS, memory, build, and game-state context, folds duplicates into one grouped issue with an occurrence count, and ties each to the build it first appeared on — so you fix the problem that hurts the most players first and confirm it is gone when its signature disappears from the next release.
Most of the time the fix is small. Seeing the failure clearly is the part that actually costs you.