Socket Client Setup & Authentication

This guide explains how to initialize the Socket.IO client on the frontend

Authentication Mechanism

  • For the socket connection to be authenticated, this cookie MUST be sent with the handshake request.

Installation

npm install socket.io-client
# or
yarn add socket.io-client

Initialization Code

To ensure cookies are sent, you must set withCredentials: true.

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);
});