skip to Main Content

I keep getting the error: "WebSocket is closed before the connection is established" logged to my console when I run my vite application. I have tried everything I know to solve this error but to no avail and I have run out of ideas on how to debug and solve the error. Below is the code from where I am initializing the websocket connection

import useSocket from "@/utils/socket";
import { createContext, useCallback, useEffect, useRef, useState } from "react";
import { AppContext } from "./context";
import { useCookies } from "react-cookie";
import { io } from "socket.io-client";
import { Socket } from "socket.io-client";
import { DefaultEventsMap } from "socket.io";


export const ContextProvider = ({children}) => {
    
    const [cookies] = useCookies(['token'])
    const [isConnected, setIsConnected] = useState(false)
    const [socket, setSocket] = useState<Socket<DefaultEventsMap, DefaultEventsMap> | null>(null)


    const [onlineCount, setOnlineCount] = useState(0)

     useEffect(() => {
        let newSocket: Socket<DefaultEventsMap, DefaultEventsMap> | null = null;

        if (cookies.token) {
            console.log(cookies.token)
            newSocket = io({
                auth: cookies.token,
                reconnection: true, // Enables automatic reconnection
                reconnectionAttempts: 5, // Number of retry attempts
                reconnectionDelay: 1000, 
            });

            console.log("connect")
            newSocket.on("connect", () => {
                console.log("Socket connected")
                setIsConnected(true)
                setSocket(newSocket)
            })
            console.log("connected")

            newSocket.on("connect_error", (error) => {
                console.error("Connection Error:", error.message);
            });

            newSocket.on('disconnect', (reason) => {
                console.log("Socket disconnected", reason)
                setIsConnected(false)
                setSocket(null)
            });

            return () => {
                if(newSocket) {
                    newSocket.disconnect()
                }
                
            }
        }
    }, [cookies.token])

    

    const contextValue = {socket}

    return (
        <AppContext.Provider value={contextValue}>
            {children}
        </AppContext.Provider>
    )
}

2

Answers


  1. Chances are your cleanup function from your useEffect hook is running and trying to disconnect your websocket. You should only disconnect your websocket if the connection has actually been established, so change it to:

    return () => {
      if(newSocket && isConnected) {
        newSocket.disconnect()
      }
    }
    

    Note you might have to also modify your connect listener to disconnect if the component has been cleaned up before the connection was established.

    Login or Signup to reply.
  2. In your WebSocket initialization code, the authentication token should be passed correctly within the auth object. Your current usage looks potentially incorrect. It should be like this:

    newSocket = io(process.env.REACT_APP_SOCKET_URL, {
        auth: {
            token: cookies.token
        },
        reconnection: true,
        reconnectionAttempts: 5,
        reconnectionDelay: 1000,
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search