Socket.IO Client
Socket.IO Client is a JavaScript library designed for facilitating real-time, bidirectional, and event-based communication between web clients (browsers or Node.js applications) and a Socket.IO server. It abstracts away the complexities of WebSocket and HTTP long-polling, providing automatic fallback mechanisms, robust reconnection logic, and packet buffering to ensure reliable connectivity even in unstable network conditions. The current stable version, 4.8.3, is part of the actively developed Socket.IO v4 ecosystem. Releases are typically aligned with the server-side `socket.io` package, focusing on bug fixes, performance improvements, and dependency updates. Its key differentiators include its focus on cross-platform compatibility, simplified API for event handling, and built-in reliability features that make it a go-to choice for real-time applications requiring persistent connections.
Common errors
-
io is not a function
cause Attempting to import `io` as a default export in CommonJS or an incorrect named import.fixFor CommonJS, use `const { io } = require('socket.io-client');`. For ESM, ensure `import { io } from 'socket.io-client';`. -
WebSocket connection to 'ws://localhost:3000/socket.io/?EIO=4&transport=websocket' failed: Error during WebSocket handshake: Unexpected response code: 400
cause The Socket.IO server is either not running, not listening on the specified port/path, or the client/server major versions are mismatched.fixVerify the server is running and accessible. Check the server logs for errors. Ensure `socket.io-client` and `socket.io` server versions are compatible (e.g., both v4). -
Access to XMLHttpRequest at 'http://localhost:3000/socket.io/?EIO=4&transport=polling&t=N24sJ1p' from origin 'http://localhost:5173' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
cause The client application's origin does not match the server's origin, and the server's CORS policy does not allow the client's origin.fixConfigure CORS on your Socket.IO server to allow requests from the client's origin. For example: `new Server(httpServer, { cors: { origin: "http://localhost:5173", methods: ["GET", "POST"] } });`
Warnings
- breaking Major protocol changes between Socket.IO v2, v3, and v4. A client from v2/v3 will not connect to a v4 server, and vice versa. Ensure your client and server versions match the major version (e.g., v4 client with v4 server).
- breaking Since `socket.io-client` v3, the main `io` function is a named export. This changes how it's imported in both ESM and CommonJS.
- security A critical vulnerability (CVE-2026-33151) was found in `socket.io-parser` (a dependency), which could lead to denial of service due to an unbounded number of binary attachments. This affects several `socket.io-parser` versions.
- gotcha When connecting from a browser to a server on a different origin (domain, port, or protocol), you must configure Cross-Origin Resource Sharing (CORS) on the server-side. Otherwise, connection attempts will be blocked by the browser.
Install
-
npm install socket.io-client -
yarn add socket.io-client -
pnpm add socket.io-client
Imports
- io
const io = require('socket.io-client');import { io } from 'socket.io-client'; - Socket
import type { Socket } from 'socket.io-client'; - Manager
const Manager = require('socket.io-client').Manager;import { Manager } from 'socket.io-client';
Quickstart
import { io, Socket } from 'socket.io-client';
// Connect to a Socket.IO server running on localhost:3000
const socket: Socket = io('http://localhost:3000');
// Event listener for successful connection
socket.on('connect', () => {
console.log(`Connected to the server with ID: ${socket.id}`);
// Emit a 'greeting' event to the server
socket.emit('greeting', 'Hello from the client!');
});
// Event listener for incoming 'message' events from the server
socket.on('message', (data: string) => {
console.log('Received message:', data);
});
// Event listener for disconnection
socket.on('disconnect', (reason: Socket.DisconnectReason) => {
console.log(`Disconnected from the server: ${reason}`);
});
// Event listener for connection errors
socket.on('connect_error', (error: Error) => {
console.error('Connection error:', error.message);
});
// Manually disconnect after 15 seconds (optional)
setTimeout(() => {
if (socket.connected) {
console.log('Manually disconnecting after 15 seconds...');
socket.disconnect();
}
}, 15000);