Refactor WebSocket URL handling in useWebSocket hook to support both absolute and relative API URLs, improving flexibility and error handling for host resolution.

This commit is contained in:
PEDZEO
2026-01-19 01:40:50 +03:00
parent d55c6ea532
commit 3fc22d2b4d

View File

@@ -60,9 +60,19 @@ export function useWebSocket(options: UseWebSocketOptions = {}) {
// Build WebSocket URL // Build WebSocket URL
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:' const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'
const host = import.meta.env.VITE_API_URL let host = window.location.host
? new URL(import.meta.env.VITE_API_URL).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}` const wsUrl = `${protocol}//${host}/cabinet/ws?token=${accessToken}`
try { try {