Maaz Zindani

Loading the index…

↑↓ move↵ openesc close4791 pages
Node.js, PHP and APIs

Socket.IO in React logs that the WebSocket was closed before the connection was established

Your error

WebSocket connection to 'ws://localhost:3000/socket.io/?EIO=4&transport=websocket' failed: WebSocket is closed before the connection is established.1 more line it can show

Fix it fast

Most common cause, 1 of 2

Strict Mode runs the connect effect twice in development

Keep the cleanup: it is correct, and the warning is a development-only side effect.

Fix
// src/socket.js
import { io } from "socket.io-client";
export const socket = io("http://localhost:3000", { autoConnect: false });

// in the component
useEffect(() => {
  socket.connect();
  return () => {
    socket.disconnect();
  };
}, []);
Did this fix it?
Full steps for this cause: check, fix, verify

Short answer

Chrome logs "WebSocket is closed before the connection is established" only when page code calls close() on a socket that is still connecting. With Socket.IO 4.8 and React 19, that call is socket.disconnect() in an effect cleanup: the extra development run from Strict Mode, or an effect whose dependency changes every render. Create the socket once and depend on primitives.

  • Applies to Socket.IO 4.8 (server and client), React 19, Chrome and Edge
  • Updated
  • By Maaz Zindani, Senior Software Engineer

Which cause do you have?

Log the lifecycle of the socket and reload the page. A disconnect with reason io client disconnect means your own code called socket.disconnect(); count how often the effect runs to see which cause below applies.

Run this first
socket.on("connect", () => console.log("connected", socket.id));
socket.on("disconnect", (reason) => console.log("disconnect:", reason));
socket.on("connect_error", (err) => console.log("connect_error:", err.message));

Then find the line you see in this list and open its fix:

  1. 1Strict Mode runs the connect effect twice in developmentExactly one warning per page load, only with npm run dev, and the next attempt connects
  2. 2An effect dependency changes on every render, so the socket reconnects again and againThe warning repeats while you type or as state updates, and the server logs a burst of short connections

What does the error look like?

  • WebSocket connection to 'ws://localhost:3000/socket.io/?EIO=4&transport=websocket' failed: WebSocket is closed before the connection is established.
  • The warning appears once on page load in development, then the socket connects

Cause 1 of 2

Strict Mode runs the connect effect twice in development

You seeExactly one warning per page load, only with npm run dev, and the next attempt connects

Check

A single closed-before-established warning in development comes from Strict Mode, which mounts each component, runs the effect cleanup, then runs the effect again. An effect that calls socket.connect() and returns socket.disconnect() therefore opens a WebSocket and closes it at once, while the handshake is still in flight. Chromium logs this exact warning for a close() call made in the CONNECTING state.

Check
// main.jsx or index.jsx: look for the wrapper
grep -rn "StrictMode" src/

Fix

Keep the cleanup: it is correct, and the warning is a development-only side effect. Create one socket in its own module with autoConnect off, connect it inside the effect and disconnect in the cleanup, so the second run reuses the same client instead of building a new one.

Fix
// src/socket.js
import { io } from "socket.io-client";
export const socket = io("http://localhost:3000", { autoConnect: false });

// in the component
useEffect(() => {
  socket.connect();
  return () => {
    socket.disconnect();
  };
}, []);

Verify

Build the app and serve the built files the way production does. The extra effect run is development-only, so the console stays clean and the Network tab lists a single 101 Switching Protocols for the socket.

Verify
npm run build

Confirmed by socket.io

Did this fix it?

Cause 2 of 2

An effect dependency changes on every render, so the socket reconnects again and again

You seeThe warning repeats while you type or as state updates, and the server logs a burst of short connections

Check

A warning that repeats on every update means an effect dependency changes each render: React runs the cleanup and then the setup again after every commit in which a dependency changed. An options object, an auth object or a callback declared inside the component gets a fresh identity every time it renders, so the effect disconnects the half-open socket and starts another one each time.

Check
// a pattern that reconnects after every render
const auth = { token };
useEffect(() => {
  socket.auth = auth;
  socket.connect();
  return () => socket.disconnect();
}, [auth]);

Fix

Depend on primitive values only, and build any object the socket needs inside the effect itself.

Fix
useEffect(() => {
  socket.auth = { token };
  socket.connect();
  return () => socket.disconnect();
}, [token]);

Verify

Type into a field on the page. The connect line is printed once, and the server sees one connection per user instead of one per keystroke.

Verify
socket.on("connect", () => console.count("connect"));

Confirmed by react.dev

Did this fix it?

How do I stop it coming back?

  • Create the Socket.IO client once, in a module of its own, and import it where it is needed.
  • Read the disconnect reason before changing server or proxy settings: io client disconnect always points at your own code.
  • Keep socket effects free of object and function dependencies.

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.

Which stack is behind this page?

Projects of mine on the same stack: TaxiDex, QistLock, SessionBird.

Next step

Want this handled for good?

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