Socket.IO
Socket.IO is a real-time, bidirectional, event-based communication library that enables low-latency communication between web clients and Node.js servers. It facilitates cross-browser messaging with fallback options for reliable connections, even through proxies and firewalls. The current stable version is 4.8.3, and the package receives regular patch releases for bug fixes, security updates, and dependency maintenance across its ecosystem components.
Common errors
-
Error: Server must be passed to the constructor
cause The `Server` constructor was called without an `http.Server` instance or a port number.fixInitialize the Socket.IO server with `new Server(httpServer)` or `new Server(3000)`. -
DeprecationWarning: The URL.parse() method is deprecated and will be removed in a future version. Please use the WHATWG URL API.
cause An older version of `socket.io` or its dependencies is using the deprecated `url.parse()` function in Node.js.fixUpgrade `socket.io` to version 4.8.2 or later. -
Error: connect ECONNREFUSED ::1:3000 (or similar IP/port)
cause The client attempted to connect to a Socket.IO server that is not running or is listening on a different host/port.fixEnsure the Socket.IO server is running and listening on the expected host and port. Verify the client's connection URL matches the server's address. -
TypeError: socket.on is not a function
cause Attempting to register a client-specific event listener on the `io` (Server) instance instead of an individual `socket` instance.fixAttach client-specific event listeners within the `io.on('connection', (socket) => { ... })` callback, using the `socket` object: `socket.on('eventName', handler)`. -
WebSocket connection to 'ws://localhost:3000/socket.io/?EIO=4&transport=websocket' failed: Error during WebSocket handshake: Unexpected response code: 400
cause This often indicates a Cross-Origin Resource Sharing (CORS) issue or an incorrect Engine.IO path configuration between the client and server.fixEnsure CORS options are correctly configured on the server-side, e.g., `new Server(httpServer, { cors: { origin: "*", methods: ["GET", "POST"] } })`.
Warnings
- breaking A critical security vulnerability (CVE-2026-33151) exists in the `socket.io-parser` dependency, allowing potential resource exhaustion via excessively large binary attachments.
- gotcha When deploying Socket.IO across multiple Node.js instances behind a load balancer, 'sticky sessions' are required to ensure a client's requests are always routed to the same server instance.
- deprecated Older Socket.IO versions (or their dependencies) may use Node.js's deprecated `url.parse()` function, leading to deprecation warnings in newer Node.js environments.
- gotcha Calling `io.close()` on an already stopped server instance could throw an error, potentially leading to unhandled exceptions.
Install
-
npm install socket.io -
yarn add socket.io -
pnpm add socket.io
Imports
- Server
const Server = require('socket.io');import { Server } from 'socket.io';
Quickstart
import { Server } from 'socket.io';
import { createServer } from 'http';
const httpServer = createServer();
const io = new Server(httpServer, {
cors: {
origin: '*', // Allow all origins for simplicity in quickstart
methods: ['GET', 'POST']
}
});
io.on('connection', (socket) => {
console.log(`User connected: ${socket.id}`);
socket.emit('hello', `Welcome, ${socket.id}!`);
socket.on('message', (payload: string) => {
console.log(`Received message from ${socket.id}: ${payload}`);
// Broadcast the message to all connected clients
io.emit('broadcast', `Message from ${socket.id}: ${payload}`);
});
socket.on('disconnect', () => {
console.log(`User disconnected: ${socket.id}`);
});
});
const PORT = process.env.PORT ?? 3000;
httpServer.listen(PORT, () => {
console.log(`Socket.IO server listening on port ${PORT}`);
});