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";
// URL of your backend
const SOCKET_URL = process.env.NEXT_PUBLIC_API_URL || "http://localhost:4000";
// Retrieve the token from wherever you stored it (e.g., localStorage)
const token = localStorage.getItem("jwt_token");
export const socket = io(SOCKET_URL, {
path: "/socket.io",
// need polling as transports for authentication to work
// connection first polls and later moves to websocket connection
transports: ["websocket", "polling"],
auth: {
token: token, // Sent during the handshake for authentication
},
autoConnect: true,
});
socket.on("connect", () => {
console.log("Connected with ID:", socket.id);
});
socket.on("connect_error", err => {
console.error("Connection failed:", err.message);
// If error is 'Unauthorized', handle re-login
});React Hook / Context Pattern
Last updated