Skip to main content
Version: 4.x

The Socket instance (client-side)

A Socket is the fundamental class for interacting with the server. It inherits most of the methods of the Node.js EventEmitter, like emit, on, once or off.

Bidirectional communication between server and clientBidirectional communication between server and client

Besides emitting and listening to events, the Socket instance has a few attributes that may be of use in your application:

Socket#id

Each new connection is assigned a random 20-characters identifier.

This identifier is synced with the value on the server-side.

// server-side
io.on("connection", (socket) => {
console.log(socket.id); // x8WIv7-mJelg7on_ALbx
});

// client-side
socket.on("connect", () => {
console.log(socket.id); // x8WIv7-mJelg7on_ALbx
});

socket.on("disconnect", () => {
console.log(socket.id); // undefined
});
caution

Please note that, unless connection state recovery is enabled, the id attribute is an ephemeral ID that is not meant to be used in your application (or only for debugging purposes) because:

  • this ID is regenerated after each reconnection (for example when the WebSocket connection is severed, or when the user refreshes the page)
  • two different browser tabs will have two different IDs
  • there is no message queue stored for a given ID on the server (i.e. if the client is disconnected, the messages sent from the server to this ID are lost)

Please use a regular session ID instead (either sent in a cookie, or stored in the localStorage and sent in the auth payload).

See also:

Socket#connected

This attribute describes whether the socket is currently connected to the server.

socket.on("connect", () => {
console.log(socket.connected); // true
});

socket.on("disconnect", () => {
console.log(socket.connected); // false
});

Socket#io

A reference to the underlying Manager.

socket.on("connect", () => {
const engine = socket.io.engine;
console.log(engine.transport.name); // in most cases, prints "polling"

engine.once("upgrade", () => {
// called when the transport is upgraded (i.e. from HTTP long-polling to WebSocket)
console.log(engine.transport.name); // in most cases, prints "websocket"
});

engine.on("packet", ({ type, data }) => {
// called for each packet received
});

engine.on("packetCreate", ({ type, data }) => {
// called for each packet sent
});

engine.on("drain", () => {
// called when the write buffer is drained
});

engine.on("close", (reason) => {
// called when the underlying connection is closed
});
});

Lifecycle

Lifecycle diagramLifecycle diagram

Events

The Socket instance emits three special events:

tip

Since Socket.IO v3, the Socket instance does not emit any event related to the reconnection logic anymore. You can listen to the events on the Manager instance directly:

socket.io.on("reconnect_attempt", () => {
// ...
});

socket.io.on("reconnect", () => {
// ...
});

More information can be found in the migration guide.

connect

This event is fired by the Socket instance upon connection and reconnection.

socket.on("connect", () => {
// ...
});
caution

Event handlers shouldn't be registered in the connect handler itself, as a new handler will be registered every time the socket instance reconnects:

BAD ⚠️

socket.on("connect", () => {
socket.on("data", () => { /* ... */ });
});

GOOD 👍

socket.on("connect", () => {
// ...
});

socket.on("data", () => { /* ... */ });

connect_error

This event is fired upon connection failure.

ReasonAutomatic reconnection?
The low-level connection cannot be established (temporary failure)✅ YES
The connection was denied by the server in a middleware function❌ NO

The socket.active attribute indicates whether the socket will automatically try to reconnect after a small randomized delay:

socket.on("connect_error", (error) => {
if (socket.active) {
// temporary failure, the socket will automatically try to reconnect
} else {
// the connection was denied by the server
// in that case, `socket.connect()` must be manually called in order to reconnect
console.log(error.message);
}
});

disconnect

  • reason <string>
  • details <DisconnectDetails>

This event is fired upon disconnection.

socket.on("disconnect", (reason, details) => {
// ...
});

Here is the list of possible reasons:

ReasonDescriptionAutomatic reconnection?
io server disconnectThe server has forcefully disconnected the socket with socket.disconnect()❌ NO
io client disconnectThe socket was manually disconnected using socket.disconnect()❌ NO
ping timeoutThe server did not send a PING within the pingInterval + pingTimeout range✅ YES
transport closeThe connection was closed (example: the user has lost connection, or the network was changed from WiFi to 4G)✅ YES
transport errorThe connection has encountered an error (example: the server was killed during a HTTP long-polling cycle)✅ YES

The socket.active attribute indicates whether the socket will automatically try to reconnect after a small randomized delay:

socket.on("disconnect", (reason) => {
if (socket.active) {
// temporary disconnection, the socket will automatically try to reconnect
} else {
// the connection was forcefully closed by the server or the client itself
// in that case, `socket.connect()` must be manually called in order to reconnect
console.log(reason);
}
});
caution

The following event names are reserved and must not be used in your application:

  • connect
  • connect_error
  • disconnect
  • disconnecting
  • newListener
  • removeListener
// BAD, will throw an error
socket.emit("disconnect");

Complete API

The complete API exposed by the Socket instance can be found here.