From 57b09b1f997ea7efc7cd5f879563b7233d5710b2 Mon Sep 17 00:00:00 2001 From: hobokenchicken Date: Wed, 22 Apr 2026 14:02:40 -0400 Subject: [PATCH] fix: socket reconnect and polling fallback --- frontend/src/lib/socket.ts | 62 ++++++++++++++++++++------------------ 1 file changed, 33 insertions(+), 29 deletions(-) diff --git a/frontend/src/lib/socket.ts b/frontend/src/lib/socket.ts index dd21c47..d33f887 100644 --- a/frontend/src/lib/socket.ts +++ b/frontend/src/lib/socket.ts @@ -1,38 +1,42 @@ -import { useEffect, useRef } from 'react'; -import { io, Socket } from 'socket.io-client'; -import { useStore } from './store'; +import { useEffect, useRef } from "react"; +import { io, type Socket } from "socket.io-client"; +import { useStore } from "./store"; -const SOCKET_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3001'; +const SOCKET_URL = + typeof window !== "undefined" + ? window.location.origin + : process.env.NEXT_PUBLIC_API_URL || "http://localhost:3000"; export const useSocket = () => { - const { token, isAuthenticated } = useStore(); - const socketRef = useRef(null); + const { token, isAuthenticated } = useStore(); + const socketRef = useRef(null); - useEffect(() => { - if (isAuthenticated && token) { - // Connect to socket - socketRef.current = io(SOCKET_URL, { - auth: { token }, - transports: ['websocket'], - }); + useEffect(() => { + if (isAuthenticated && token) { + socketRef.current = io(SOCKET_URL, { + auth: { token }, + transports: ["websocket", "polling"], + path: "/socket.io", + reconnection: true, + }); - socketRef.current.on('connect', () => { - console.log('Connected to socket'); - socketRef.current?.emit('subscribe_transactions'); - }); + socketRef.current.on("connect", () => { + console.log("Connected to socket"); + socketRef.current?.emit("subscribe_transactions"); + }); - socketRef.current.on('connect_error', (error) => { - console.error('Socket connection error:', error); - }); + socketRef.current.on("connect_error", (error) => { + console.error("Socket connection error:", error); + }); - return () => { - if (socketRef.current) { - socketRef.current.disconnect(); - socketRef.current = null; - } - }; - } - }, [isAuthenticated, token]); + return () => { + if (socketRef.current) { + socketRef.current.disconnect(); + socketRef.current = null; + } + }; + } + }, [isAuthenticated, token]); - return socketRef.current; + return socketRef.current; };