Server API

Server

Exposed by require("socket.io").

Related documentation pages:

new Server(httpServer[, options])

  • httpServer (http.Server) the server to bind to.
  • options (Object)

Works with and without new:

  1. const io = require("socket.io")();
  2. // or
  3. const { Server } = require("socket.io");
  4. const io = new Server();

Available options:

OptionDefault valueDescription
path/socket.ioname of the path to capture
serveClienttruewhether to serve the client files
adapter-the adapter to use. Defaults to an instance of the Adapter that ships with socket.io which is memory based. See socket.io-adapter
parser-the parser to use. Defaults to an instance of the Parser that ships with socket.io. See socket.io-parser.
connectTimeout45000the number of ms before closing a client that has not successfully joined a namespace.

Available options for the underlying Engine.IO server:

OptionDefault valueDescription
pingTimeout5000how many ms without a pong packet to consider the connection closed
pingInterval25000how many ms before sending a new ping packet
upgradeTimeout10000how many ms before an uncompleted transport upgrade is cancelled
maxHttpBufferSize1e6how many bytes or characters a message can be, before closing the session (to avoid DoS).
allowRequestA function that receives a given handshake or upgrade request as its first parameter, and can decide whether to continue or not. The second argument is a function that needs to be called with the decided information: fn(err, success), where success is a boolean value where false means that the request is rejected, and err is an error code.
transports[“polling”, “websocket”]transports to allow connections to
allowUpgradestruewhether to allow transport upgrades
perMessageDeflatefalseparameters of the WebSocket permessage-deflate extension (see ws module api docs). Set to true to enable.
httpCompressiontrueparameters of the http compression for the polling transports (see zlib api docs). Set to false to disable.
wsEnginewswhat WebSocket server implementation to use. Specified module must conform to the ws interface (see ws module api docs). Default value is ws. An alternative c++ addon is also available by installing the eiows module.
corsthe list of options that will be forwarded to the cors module
cookiethe list of options that will be forwarded to the cookie module
allowEIO3falsewhether to enable compatibility with Socket.IO v2 clients

More information here.

new Server(port[, options])

  • port (Number) a port to listen to (a new http.Server will be created)
  • options (Object)

See above for the list of available options.

  1. const io = require("socket.io")(3000, {
  2. path: "/test",
  3. serveClient: false,
  4. // below are engine.IO options
  5. pingInterval: 10000,
  6. pingTimeout: 5000,
  7. cookie: false
  8. });

new Server(options)

  • options (Object)

See above for the list of available options.

  1. const io = require("socket.io")({
  2. path: "/test",
  3. serveClient: false,
  4. });
  5. // either
  6. const server = require("http").createServer();
  7. io.attach(server, {
  8. pingInterval: 10000,
  9. pingTimeout: 5000,
  10. cookie: false
  11. });
  12. server.listen(3000);
  13. // or
  14. io.attach(3000, {
  15. pingInterval: 10000,
  16. pingTimeout: 5000,
  17. cookie: false
  18. });

server.sockets

  • (Namespace)

An alias for the default (/) namespace.

  1. io.sockets.emit("hi", "everyone");
  2. // is equivalent to
  3. io.of("/").emit("hi", "everyone");

server.serveClient([value])

  • value (Boolean)
  • Returns Server|Boolean

If value is true the attached server (see Server#attach) will serve the client files. Defaults to true. This method has no effect after attach is called. If no arguments are supplied this method returns the current value.

  1. // pass a server and the `serveClient` option
  2. const io = require("socket.io")(http, { serveClient: false });
  3. // or pass no server and then you can call the method
  4. const io = require("socket.io")();
  5. io.serveClient(false);
  6. io.attach(http);

server.path([value])

  • value (String)
  • Returns Server|String

Sets the path value under which engine.io and the static files will be served. Defaults to /socket.io. If no arguments are supplied this method returns the current value.

  1. const io = require("socket.io")();
  2. io.path("/myownpath");
  3. // client-side
  4. const socket = io({
  5. path: "/myownpath"
  6. });

server.adapter([value])

  • value (Adapter)
  • Returns Server|Adapter

Sets the adapter value. Defaults to an instance of the Adapter that ships with socket.io which is memory based. See socket.io-adapter. If no arguments are supplied this method returns the current value.

  1. const io = require("socket.io")(3000);
  2. const redis = require("socket.io-redis");
  3. io.adapter(redis({ host: "localhost", port: 6379 }));

server.attach(httpServer[, options])

  • httpServer (http.Server) the server to attach to
  • options (Object)

Attaches the Server to an engine.io instance on httpServer with the supplied options (optionally).

server.attach(port[, options])

  • port (Number) the port to listen on
  • options (Object)

Attaches the Server to an engine.io instance on a new http.Server with the supplied options (optionally).

server.listen(httpServer[, options])

Synonym of server.attach(httpServer[, options]).

server.listen(port[, options])

Synonym of server.attach(port[, options]).

server.bind(engine)

  • engine (engine.Server)
  • Returns Server

Advanced use only. Binds the server to a specific engine.io Server (or compatible API) instance.

server.onconnection(socket)

  • socket (engine.Socket)
  • Returns Server

Advanced use only. Creates a new socket.io client from the incoming engine.io (or compatible API) Socket.

server.of(nsp)

  • nsp (String|RegExp|Function)
  • Returns Namespace

Initializes and retrieves the given Namespace by its pathname identifier nsp. If the namespace was already initialized it returns it immediately.

  1. const adminNamespace = io.of("/admin");

A regex or a function can also be provided, in order to create namespace in a dynamic way:

  1. const dynamicNsp = io.of(/^\/dynamic-\d+$/).on("connection", (socket) => {
  2. const newNamespace = socket.nsp; // newNamespace.name === "/dynamic-101"
  3. // broadcast to all clients in the given sub-namespace
  4. newNamespace.emit("hello");
  5. });
  6. // client-side
  7. const socket = io("/dynamic-101");
  8. // broadcast to all clients in each sub-namespace
  9. dynamicNsp.emit("hello");
  10. // use a middleware for each sub-namespace
  11. dynamicNsp.use((socket, next) => { /* ... */ });

With a function:

  1. io.of((name, query, next) => {
  2. // the checkToken method must return a boolean, indicating whether the client is able to connect or not.
  3. next(null, checkToken(query.token));
  4. }).on("connection", (socket) => { /* ... */ });

server.close([callback])

  • callback (Function)

Closes the Socket.IO server. The callback argument is optional and will be called when all connections are closed.

Note: this also closes the underlying HTTP server.

  1. const Server = require("socket.io");
  2. const PORT = 3030;
  3. const server = require("http").Server();
  4. const io = Server(PORT);
  5. io.close(); // Close current server
  6. server.listen(PORT); // PORT is free to use
  7. io = Server(server);

server.engine.generateId

Overwrites the default method to generate your custom socket id.

The function is called with a node request object (http.IncomingMessage) as first parameter.

  1. const uuid = require("uuid");
  2. io.engine.generateId = (req) => {
  3. return uuid.v4(); // must be unique across all Socket.IO servers
  4. }

Namespace

Represents a pool of sockets connected under a given scope identified by a pathname (eg: /chat).

More information can be found here.

namespace.name

  • (String)

The namespace identifier property.

namespace.sockets

  • (Map<SocketId, Socket>)

A map of Socket instances that are connected to this namespace.

  1. // number of sockets in this namespace (on this node)
  2. const socketCount = io.of("/admin").sockets.size;

namespace.adapter

  • (Adapter)

The “Adapter” used for the namespace. Useful when using the Adapter based on Redis, as it exposes methods to manage sockets and rooms across your cluster.

Note: the adapter of the main namespace can be accessed with io.of("/").adapter.

Please see the explanation here.

namespace.to(room)

  • room (String)
  • Returns Namespace for chaining

Sets a modifier for a subsequent event emission that the event will only be broadcasted to clients that have joined the given room.

To emit to multiple rooms, you can call to several times.

  1. const io = require("socket.io")();
  2. const adminNamespace = io.of("/admin");
  3. adminNamespace.to("level1").emit("an event", { some: "data" });

namespace.in(room)

Synonym of namespace.to(room).

namespace.emit(eventName[, …args])

  • eventName (String)
  • args
  • Returns true

Emits an event to all connected clients. The following two are equivalent:

  1. const io = require("socket.io")();
  2. io.emit("an event sent to all connected clients"); // main namespace
  3. const chat = io.of("/chat");
  4. chat.emit("an event sent to all connected clients in chat namespace");

Note: acknowledgements are not supported when emitting from namespace.

namespace.allSockets()

  • Returns Promise<Set<SocketId>>

Gets a list of socket IDs connected to this namespace (across all nodes if applicable).

  1. // all sockets in the main namespace
  2. const ids = await io.allSockets();
  3. // all sockets in the main namespace and in the "user:1234" room
  4. const ids = await io.in("user:1234").allSockets();
  5. // all sockets in the "chat" namespace
  6. const ids = await io.of("/chat").allSockets();
  7. // all sockets in the "chat" namespace and in the "general" room
  8. const ids = await io.of("/chat").in("general").allSockets();

namespace.use(fn)

  • fn (Function)

Registers a middleware, which is a function that gets executed for every incoming Socket, and receives as parameters the socket and a function to optionally defer execution to the next registered middleware.

Errors passed to middleware callbacks are sent as special connect_error packets to clients.

  1. // server-side
  2. io.use((socket, next) => {
  3. const err = new Error("not authorized");
  4. err.data = { content: "Please retry later" }; // additional details
  5. next(err);
  6. });
  7. // client-side
  8. socket.on("connect_error", err => {
  9. console.log(err instanceof Error); // true
  10. console.log(err.message); // not authorized
  11. console.log(err.data); // { content: "Please retry later" }
  12. });

Event: ‘connection’

  • socket (Socket) socket connection with client

Fired upon a connection from client.

  1. io.on("connection", (socket) => {
  2. // ...
  3. });
  4. io.of("/admin").on("connection", (socket) => {
  5. // ...
  6. });

Event: ‘connect’

Synonym of Event: “connection”.

Flag: ‘volatile’

Sets a modifier for a subsequent event emission that the event data may be lost if the clients are not ready to receive messages (because of network slowness or other issues, or because they’re connected through long polling and is in the middle of a request-response cycle).

  1. io.volatile.emit("an event", { some: "data" }); // the clients may or may not receive it

Flag: ‘local’

Sets a modifier for a subsequent event emission that the event data will only be broadcast to the current node (when the Redis adapter is used).

  1. io.local.emit("an event", { some: "data" });

Socket

A Socket is the fundamental class for interacting with browser clients. A Socket belongs to a certain Namespace (by default /) and uses an underlying Client to communicate.

It should be noted the Socket doesn’t relate directly to the actual underlying TCP/IP socket and it is only the name of the class.

Within each Namespace, you can also define arbitrary channels (called room) that the Socket can join and leave. That provides a convenient way to broadcast to a group of Sockets (see Socket#to below).

The Socket class inherits from EventEmitter. The Socket class overrides the emit method, and does not modify any other EventEmitter method. All methods documented here which also appear as EventEmitter methods (apart from emit) are implemented by EventEmitter, and documentation for EventEmitter applies.

More information can be found here.

socket.id

  • (String)

A unique identifier for the session, that comes from the underlying Client.

socket.rooms

  • (Set)

A Set of strings identifying the rooms this client is in.

  1. io.on("connection", (socket) => {
  2. console.log(socket.rooms); // Set { <socket.id> }
  3. socket.join("room1");
  4. console.log(socket.rooms); // Set { <socket.id>, "room1" }
  5. });

socket.client

  • (Client)

A reference to the underlying Client object.

socket.conn

  • (engine.Socket)

A reference to the underlying Client transport connection (engine.io Socket object). This allows access to the IO transport layer, which still (mostly) abstracts the actual TCP/IP socket.

socket.request

  • (Request)

A getter proxy that returns the reference to the request that originated the underlying engine.io Client. Useful for accessing request headers such as Cookie or User-Agent.

  1. const cookie = require("cookie");
  2. io.on("connection", (socket) => {
  3. const cookies = cookie.parse(socket.request.headers.cookie || "");
  4. });

socket.handshake

  • (Object)

The handshake details:

  1. {
  2. headers: /* the headers sent as part of the handshake */,
  3. time: /* the date of creation (as string) */,
  4. address: /* the ip of the client */,
  5. xdomain: /* whether the connection is cross-domain */,
  6. secure: /* whether the connection is secure */,
  7. issued: /* the date of creation (as unix timestamp) */,
  8. url: /* the request URL string */,
  9. query: /* the query params of the first request */,
  10. auth: /* the authentication payload */
  11. }

Usage:

  1. io.use((socket, next) => {
  2. let handshake = socket.handshake;
  3. // ...
  4. });
  5. io.on("connection", (socket) => {
  6. let handshake = socket.handshake;
  7. // ...
  8. });

socket.use(fn)

History

VersionChanges
v3.0.5Restoration of the first implementation.
v3.0.0Removal in favor of socket.onAny().
v1.7.2The error event is sent directly to the client.
v1.6.0First implementation.
  • fn (Function)

Registers a middleware, which is a function that gets executed for every incoming Packet and receives as parameter the packet and a function to optionally defer execution to the next registered middleware.

Errors passed to the middleware callback are then emitted as error events on the server-side:

  1. io.on("connection", (socket) => {
  2. socket.use(([event, ...args], next) => {
  3. if (isUnauthorized(event)) {
  4. return next(new Error("unauthorized event"));
  5. }
  6. // do not forget to call next
  7. next();
  8. });
  9. socket.on("error", (err) => {
  10. if (err && err.message === "unauthorized event") {
  11. socket.disconnect();
  12. }
  13. });
  14. });

socket.send([…args][, ack])

  • args
  • ack (Function)
  • Returns Socket

Sends a message event. See socket.emit(eventName[, …args][, ack]).

socket.emit(eventName[, …args][, ack])

(overrides EventEmitter.emit)

  • eventName (String)
  • args
  • ack (Function)
  • Returns true

Emits an event to the socket identified by the string name. Any other parameters can be included. All serializable data structures are supported, including Buffer.

  1. socket.emit("hello", "world");
  2. socket.emit("with-binary", 1, "2", { 3: "4", 5: Buffer.from([6]) });

The ack argument is optional and will be called with the client’s answer.

  1. io.on("connection", (socket) => {
  2. socket.emit("an event", { some: "data" });
  3. socket.emit("ferret", "tobi", (data) => {
  4. console.log(data); // data will be "woot"
  5. });
  6. // the client code
  7. // client.on("ferret", (name, fn) => {
  8. // fn("woot");
  9. // });
  10. });

socket.on(eventName, callback)

(inherited from EventEmitter)

  • eventName (String)
  • callback (Function)
  • Returns Socket

Register a new handler for the given event.

  1. socket.on("news", (data) => {
  2. console.log(data);
  3. });
  4. // with several arguments
  5. socket.on("news", (arg1, arg2, arg3) => {
  6. // ...
  7. });
  8. // or with acknowledgement
  9. socket.on("news", (data, callback) => {
  10. callback(0);
  11. });

socket.once(eventName, listener)

socket.removeListener(eventName, listener)

socket.removeAllListeners([eventName])

socket.eventNames()

Inherited from EventEmitter (along with other methods not mentioned here). See the Node.js documentation for the events module.

socket.onAny(callback)

  • callback (Function)

Register a new catch-all listener.

  1. socket.onAny((event, ...args) => {
  2. console.log(`got ${event}`);
  3. });

socket.prependAny(callback)

  • callback (Function)

Register a new catch-all listener. The listener is added to the beginning of the listeners array.

  1. socket.prependAny((event, ...args) => {
  2. console.log(`got ${event}`);
  3. });

socket.offAny([listener])

  • listener (Function)

Removes the previously registered listener. If no listener is provided, all catch-all listeners are removed.

  1. const myListener = () => { /* ... */ };
  2. socket.onAny(myListener);
  3. // then, later
  4. socket.offAny(myListener);
  5. socket.offAny();

socket.listenersAny()

  • Returns Function[]

Returns the list of registered catch-all listeners.

  1. const listeners = socket.listenersAny();

socket.join(room)

  • room (string) | (string[])
  • Returns void | Promise

Adds the socket to the given room or to the list of rooms.

  1. io.on("connection", (socket) => {
  2. socket.join("room 237");
  3. console.log(socket.rooms); // Set { <socket.id>, "room 237" }
  4. socket.join(["room 237", "room 238"]);
  5. io.to("room 237").emit("a new user has joined the room"); // broadcast to everyone in the room
  6. });

The mechanics of joining rooms are handled by the Adapter that has been configured (see Server#adapter above), defaulting to socket.io-adapter.

For your convenience, each socket automatically joins a room identified by its id (see Socket#id). This makes it easy to broadcast messages to other sockets:

  1. io.on("connection", (socket) => {
  2. socket.on("say to someone", (id, msg) => {
  3. // send a private message to the socket with the given id
  4. socket.to(id).emit("my message", msg);
  5. });
  6. });

socket.leave(room)

  • room (String)
  • Returns void | Promise

Removes the socket from the given room.

  1. io.on("connection", (socket) => {
  2. socket.leave("room 237");
  3. io.to("room 237").emit(`user ${socket.id} has left the room`);
  4. });

Rooms are left automatically upon disconnection.

socket.to(room)

  • room (String)
  • Returns Socket for chaining

Sets a modifier for a subsequent event emission that the event will only be broadcasted to clients that have joined the given room (the socket itself being excluded).

To emit to multiple rooms, you can call to several times.

  1. io.on("connection", (socket) => {
  2. // to one room
  3. socket.to("others").emit("an event", { some: "data" });
  4. // to multiple rooms
  5. socket.to("room1").to("room2").emit("hello");
  6. // a private message to another socket
  7. socket.to(/* another socket id */).emit("hey");
  8. // WARNING: `socket.to(socket.id).emit()` will NOT work, as it will send to everyone in the room
  9. // named `socket.id` but the sender. Please use the classic `socket.emit()` instead.
  10. });

Note: acknowledgements are not supported when broadcasting.

socket.in(room)

Synonym of socket.to(room).

socket.compress(value)

  • value (Boolean) whether to following packet will be compressed
  • Returns Socket for chaining

Sets a modifier for a subsequent event emission that the event data will only be compressed if the value is true. Defaults to true when you don’t call the method.

  1. io.on("connection", (socket) => {
  2. socket.compress(false).emit("uncompressed", "that's rough");
  3. });

socket.disconnect(close)

  • close (Boolean) whether to close the underlying connection
  • Returns Socket

Disconnects this socket. If value of close is true, closes the underlying connection. Otherwise, it just disconnects the namespace.

  1. io.on("connection", (socket) => {
  2. setTimeout(() => socket.disconnect(true), 5000);
  3. });

Flag: ‘broadcast’

Sets a modifier for a subsequent event emission that the event data will only be broadcast to every sockets but the sender.

  1. io.on("connection", (socket) => {
  2. socket.broadcast.emit("an event", { some: "data" }); // everyone gets it but the sender
  3. });

Flag: ‘volatile’

Sets a modifier for a subsequent event emission that the event data may be lost if the client is not ready to receive messages (because of network slowness or other issues, or because they’re connected through long polling and is in the middle of a request-response cycle).

  1. io.on("connection", (socket) => {
  2. socket.volatile.emit("an event", { some: "data" }); // the client may or may not receive it
  3. });

Event: ‘disconnect’

  • reason (String) the reason of the disconnection (either client or server-side)

Fired upon disconnection.

  1. io.on("connection", (socket) => {
  2. socket.on("disconnect", (reason) => {
  3. // ...
  4. });
  5. });

Possible reasons:

ReasonDescription
server namespace disconnectThe socket was forcefully disconnected with socket.disconnect()
client namespace disconnectThe client has manually disconnected the socket using socket.disconnect()
server shutting downThe server is, well, shutting down
ping timeoutThe client did not send a PONG packet in the pingTimeout delay
transport closeThe connection was closed (example: the user has lost connection, or the network was changed from WiFi to 4G)
transport errorThe connection has encountered an error

Event: ‘disconnecting’

  • reason (String) the reason of the disconnection (either client or server-side)

Fired when the client is going to be disconnected (but hasn’t left its rooms yet).

  1. io.on("connection", (socket) => {
  2. socket.on("disconnecting", (reason) => {
  3. console.log(socket.rooms); // Set { ... }
  4. });
  5. });

Note: those events, along with connect, connect_error, newListener and removeListener, are special events that shouldn’t be used in your application:

  1. // BAD, will throw an error
  2. socket.emit("disconnect");

Client

The Client class represents an incoming transport (engine.io) connection. A Client can be associated with many multiplexed Sockets that belong to different Namespaces.

client.conn

  • (engine.Socket)

A reference to the underlying engine.io Socket connection.

client.request

  • (Request)

A getter proxy that returns the reference to the request that originated the engine.io connection. Useful for accessing request headers such as Cookie or User-Agent.