From 3fc22d2b4de6e615c0ed15494cdde064d283f5cc Mon Sep 17 00:00:00 2001 From: PEDZEO Date: Mon, 19 Jan 2026 01:40:50 +0300 Subject: [PATCH] Refactor WebSocket URL handling in useWebSocket hook to support both absolute and relative API URLs, improving flexibility and error handling for host resolution. --- src/hooks/useWebSocket.ts | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/src/hooks/useWebSocket.ts b/src/hooks/useWebSocket.ts index 88c9887..04bb2cf 100644 --- a/src/hooks/useWebSocket.ts +++ b/src/hooks/useWebSocket.ts @@ -60,9 +60,19 @@ export function useWebSocket(options: UseWebSocketOptions = {}) { // Build WebSocket URL const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:' - const host = import.meta.env.VITE_API_URL - ? new URL(import.meta.env.VITE_API_URL).host - : window.location.host + let host = window.location.host + + // Handle VITE_API_URL - can be absolute URL or relative path + const apiUrl = import.meta.env.VITE_API_URL + if (apiUrl && (apiUrl.startsWith('http://') || apiUrl.startsWith('https://'))) { + try { + host = new URL(apiUrl).host + } catch { + // If URL parsing fails, use window.location.host + } + } + // If apiUrl is relative (like /api), use window.location.host + const wsUrl = `${protocol}//${host}/cabinet/ws?token=${accessToken}` try {