Facebook Pixel

Socket.io Summary and Complete Guide Real-Time Node.js Applications

A comprehensive summary of using Socket.io in Node.js setup, rooms, authentication, scaling, error handling, and best practices for real-time applications.

Socket.io Summary and Complete Guide

This is a complete summary of everything you need to know about Socket.io in Node.js.

Complete Setup Checklist

  • socket.io installed on server
  • socket.io-client installed on frontend
  • HTTP server created from Express app
  • Socket.io initialized with CORS config
  • JWT authentication middleware
  • Connection and disconnection handlers
  • Online users tracking (Map)
  • Event handlers (join, message, typing)
  • Room management (deterministic room IDs)
  • Input validation on all events
  • Rate limiting
  • Error handling with acknowledgments
  • Redis adapter for multi-instance scaling
  • PM2 cluster mode with Redis adapter
  • Nginx WebSocket proxy configuration
  • HTTPS/WSS in production

Architecture Summary

Frontend (React)
  ↓ socket.io-client connects with JWT auth
Socket.io Server (Node.js)
  ↓ JWT authentication middleware
  ↓ Connection handler
  ↓ Room management
  ↓ Event handlers (message, typing, presence)
Redis (for multi-instance scaling)
  ↓ Pub/sub for cross-instance broadcasting
MongoDB
  ↓ Message persistence
Nginx
  ↓ WebSocket proxy with Upgrade headers

Code Template

// Server const http = require("http"); const socketio = require("socket.io"); const { createAdapter } = require("@socket.io/redis-adapter"); const { createClient } = require("redis"); const app = require("./app"); const server = http.createServer(app); const io = socketio(server, { cors: { origin: process.env.CLIENT_URL, credentials: true }, transports: ["websocket"] }); // Redis adapter const pubClient = createClient({ url: process.env.REDIS_URL }); const subClient = pubClient.duplicate(); await Promise.all([pubClient.connect(), subClient.connect()]); io.adapter(createAdapter(pubClient, subClient)); // Auth middleware io.use(async (socket, next) => { const token = socket.handshake.auth.token; const decoded = jwt.verify(token, process.env.JWT_SECRET); socket.user = await User.findById(decoded._id); socket.userId = socket.user._id.toString(); next(); }); const onlineUsers = new Map(); io.on("connection", (socket) => { onlineUsers.set(socket.userId, socket.id); io.emit("user:online", { userId: socket.userId }); socket.on("join:chat", ({ targetUserId }) => { const roomId = [socket.userId, targetUserId].sort().join("_"); socket.join(roomId); }); socket.on("message:send", async ({ targetUserId, text }, ack) => { try { const message = await Message.create({ senderId: socket.userId, receiverId: targetUserId, text }); const roomId = [socket.userId, targetUserId].sort().join("_"); io.to(roomId).emit("message:received", message); ack({ success: true }); } catch (err) { ack({ success: false, error: err.message }); } }); socket.on("disconnect", () => { onlineUsers.delete(socket.userId); io.emit("user:offline", { userId: socket.userId }); }); }); server.listen(process.env.PORT || 3000);

Client Template

import { io } from "socket.io-client"; const socket = io(process.env.VITE_SOCKET_URL, { withCredentials: true, auth: { token: getCookie("token") }, transports: ["websocket"] }); socket.on("connect", () => { console.log("Connected:", socket.id); }); socket.on("message:received", (message) => { // Display message }); socket.on("user:online", ({ userId }) => { // Update online status }); // Send message with acknowledgment socket.emit("message:send", { targetUserId, text }, (response) => { if (response.success) { console.log("Sent!"); } });

The Takeaway

Socket.io provides real-time, bidirectional communication for Node.js. The key components are: JWT authentication middleware, room management with deterministic IDs, event handlers for messages and typing, online user tracking, Redis adapter for multi-instance scaling, PM2 cluster mode, Nginx WebSocket proxy, input validation, rate limiting, and error handling with acknowledgments. This stack powers real-time chat, notifications, and presence for the DevTinder application.

Install socket.io, create HTTP server from Express, initialize socketio with CORS and WebSocket transport, add JWT auth middleware, handle connection/disconnection, track online users, manage rooms with deterministic IDs, handle events (message, typing, presence), add Redis adapter for scaling, use PM2 cluster mode, and configure Nginx with WebSocket proxy headers.

Use the Redis adapter (@socket.io/redis-adapter) for cross-instance message broadcasting, PM2 cluster mode (instances: 'max', exec_mode: 'cluster'), Nginx with ip_hash for sticky sessions, and WebSocket proxy headers (Upgrade, Connection). Monitor connection count and memory usage.

Use io.use() middleware: read token from socket.handshake.auth.token, verify with jwt.verify(), find the user, attach to socket.user. The client passes the token in the auth option: io(url, { auth: { token } }). Handle connect_error for auth failures and redirect to login.

Create a deterministic room ID: [userId1, userId2].sort().join('_'). Both users join the same room with socket.join(roomId). Broadcast messages with io.to(roomId).emit('message:received', message). Store messages in MongoDB for persistence.

Use WebSocket transport only, Redis adapter for scaling, PM2 cluster mode, JWT auth, input validation, rate limiting, clean up on disconnect, limit message size, monitor connections and memory, handle memory leaks, use acknowledgments, rejoin rooms on reconnect, and HTTPS/WSS only.

Ready to master Node.js completely?

Want to upskill yourself, crack your next interview, and get your dream job? Join our comprehensive course to dive deeper with high-quality video tutorials, solve interview questions, and a premium community.

Please Login.
Please Login.
Please Login.
Please Login.