Files
DentalManagementMH06/apps/Frontend/src/lib/socket.js
2026-05-25 22:26:58 -04:00

29 lines
1.1 KiB
JavaScript

/**
* Shared Socket.IO client singleton.
*
* Import `socket` anywhere in the frontend to use the shared connection.
* The socket connects lazily — the first import triggers the connection.
*/
import { io } from "socket.io-client";
// Connect directly to backend to avoid Vite's WS proxy failing on upgrade,
// which causes an unhandled AggregateError from engine.io's Promise.any() probe.
// Use the env var when set; otherwise derive the backend URL from the current
// page's hostname so remote browsers (non-localhost) reach the server correctly.
const SOCKET_URL = import.meta.env.VITE_API_BASE_URL_BACKEND ||
`${window.location.protocol}//${window.location.hostname}:5000`;
export const socket = io(SOCKET_URL, {
withCredentials: true,
autoConnect: true,
reconnectionAttempts: 5,
reconnectionDelay: 2000,
});
socket.on("connect", () => {
console.log("[socket] connected:", socket.id);
});
socket.on("disconnect", () => {
console.log("[socket] disconnected");
});
socket.on("connect_error", (err) => {
console.warn("[socket] connection error:", err.message);
});