Socket Client Setup & Authentication
This guide explains how to initialize the Socket.IO client on the frontend
Authentication Mechanism
Installation
npm install socket.io-client
# or
yarn add socket.io-clientInitialization Code
Basic Setup
import { io } from "socket.io-client";
const SOCKET_URL = "https://api.yourdomain.com";
export const socket = io(SOCKET_URL, {
transports: ["websocket"], // Force WebSocket for better performance
withCredentials: true, // CRITICAL: Sends cookies (connect.sid) with request
autoConnect: true, // Connect automatically
});
socket.on("connect", () => {
console.log("Connected with ID:", socket.id);
});
socket.on("connect_error", err => {
console.error("Connection failed:", err.message);
});