从2.x迁移到3.0

This release should fix most of the inconsistencies of the Socket.IO library and provide a more intuitive behavior for the end users. It is the result of the feedback of the community over the years. A big thanks to everyone involved!

TL;DR: due to several breaking changes, a v2 client will not be able to connect to a v3 server (and vice versa)

Update: As of Socket.IO 3.1.0, the v3 server is now able to communicate with v2 clients. More information below. A v3 client is still not be able to connect to a v2 server though.

For the low-level details, please see:

Here is the complete list of changes:

Configuration

Saner default values

  • the default value of maxHttpBufferSize was decreased from 100MB to 1MB.
  • the WebSocket permessage-deflate extension is now disabled by default
  • you must now explicitly list the domains that are allowed (for CORS, see below)

CORS handling

In v2, the Socket.IO server automatically added the necessary headers to allow Cross-Origin Resource Sharing (CORS).

This behavior, while convenient, was not great in terms of security, because it meant that all domains were allowed to reach your Socket.IO server, unless otherwise specified with the origins option.

That’s why, as of Socket.IO v3:

  • CORS is now disabled by default
  • the origins option (used to provide a list of authorized domains) and the handlePreflightRequest option (used to edit the Access-Control-Allow-xxx headers) are replaced by the cors option, which will be forwarded to the cors package.

The complete list of options can be found here.

Before:

  1. const io = require("socket.io")(httpServer, {
  2. origins: ["https://example.com"],
  3. // optional, useful for custom headers
  4. handlePreflightRequest: (req, res) => {
  5. res.writeHead(200, {
  6. "Access-Control-Allow-Origin": "https://example.com",
  7. "Access-Control-Allow-Methods": "GET,POST",
  8. "Access-Control-Allow-Headers": "my-custom-header",
  9. "Access-Control-Allow-Credentials": true
  10. });
  11. res.end();
  12. }
  13. });

After:

  1. const io = require("socket.io")(httpServer, {
  2. cors: {
  3. origin: "https://example.com",
  4. methods: ["GET", "POST"],
  5. allowedHeaders: ["my-custom-header"],
  6. credentials: true
  7. }
  8. });

In previous versions, an io cookie was sent by default. This cookie can be used to enable sticky-session, which is still required when you have several servers and HTTP long-polling enabled (more information here).

However, this cookie is not needed in some cases (i.e. single server deployment, sticky-session based on IP) so it must now be explicitly enabled.

Before:

  1. const io = require("socket.io")(httpServer, {
  2. cookieName: "io",
  3. cookieHttpOnly: false,
  4. cookiePath: "/custom"
  5. });

After:

  1. const io = require("socket.io")(httpServer, {
  2. cookie: {
  3. name: "test",
  4. httpOnly: false,
  5. path: "/custom"
  6. }
  7. });

All other options (domain, maxAge, sameSite, …) are now supported. Please see here for the complete list of options.

API change

Below are listed the non backward-compatible changes.

io.set() is removed

This method was deprecated in the 1.0 release and kept for backward-compatibility. It is now removed.

It was replaced by middlewares.

Before:

  1. io.set("authorization", (handshakeData, callback) => {
  2. // make sure the handshake data looks good
  3. callback(null, true); // error first, "authorized" boolean second
  4. });

After:

  1. io.use((socket, next) => {
  2. var handshakeData = socket.request;
  3. // make sure the handshake data looks good as before
  4. // if error do this:
  5. // next(new Error("not authorized"));
  6. // else just call next
  7. next();
  8. });

No more implicit connection to the default namespace

This change impacts the users of the multiplexing feature (what we call Namespace in Socket.IO).

In previous versions, a client would always connect to the default namespace (/), even if it requested access to another namespace. This meant that the middlewares registered for the default namespace were triggered, which may be quite surprising.

  1. // client-side
  2. const socket = io("/admin");
  3. // server-side
  4. io.use((socket, next) => {
  5. // not triggered anymore
  6. });
  7. io.on("connection", socket => {
  8. // not triggered anymore
  9. })
  10. io.of("/admin").use((socket, next) => {
  11. // triggered
  12. });

Besides, we will now refer to the “main” namespace instead of the “default” namespace.

Namespace.connected is renamed to Namespace.sockets and is now a Map

The connected object (used to store all the Socket connected to the given Namespace) could be used to retrieve a Socket object from its id. It is now an ES6 Map.

Before:

  1. // get a socket by ID in the main namespace
  2. const socket = io.of("/").connected[socketId];
  3. // get a socket by ID in the "admin" namespace
  4. const socket = io.of("/admin").connected[socketId];
  5. // loop through all sockets
  6. const sockets = io.of("/").connected;
  7. for (const id in sockets) {
  8. if (sockets.hasOwnProperty(id)) {
  9. const socket = sockets[id];
  10. // ...
  11. }
  12. }
  13. // get the number of connected sockets
  14. const count = Object.keys(io.of("/").connected).length;

After:

  1. // get a socket by ID in the main namespace
  2. const socket = io.of("/").sockets.get(socketId);
  3. // get a socket by ID in the "admin" namespace
  4. const socket = io.of("/admin").sockets.get(socketId);
  5. // loop through all sockets
  6. for (const [_, socket] of io.of("/").sockets) {
  7. // ...
  8. }
  9. // get the number of connected sockets
  10. const count = io.of("/").sockets.size;

Socket.rooms is now a Set

The rooms property contains the list of rooms the Socket is currently in. It was an object, it is now an ES6 Set.

Before:

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

After:

  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.binary() is removed

The binary method could be used to indicate that a given event did not contain any binary data (in order to skip the lookup done by the library and improve performance in certain conditions).

It was replaced by the ability to provide your own parser, which was added in Socket.IO 2.0.

Before:

  1. socket.binary(false).emit("hello", "no binary");

After:

  1. const io = require("socket.io")(httpServer, {
  2. parser: myCustomParser
  3. });

Please see socket.io-msgpack-parser for example.

Socket.join() and Socket.leave() are now synchronous

The asynchronicity was needed for the first versions of the Redis adapter, but this is not the case anymore.

For reference, an Adapter is an object that stores the relationships between Sockets and Rooms. There are two official adapters: the in-memory adapter (built-in) and the Redis adapter based on Redis pub-sub mechanism.

Before:

  1. socket.join("room1", () => {
  2. io.to("room1").emit("hello");
  3. });
  4. socket.leave("room2", () => {
  5. io.to("room2").emit("bye");
  6. });

After:

  1. socket.join("room1");
  2. io.to("room1").emit("hello");
  3. socket.leave("room2");
  4. io.to("room2").emit("bye");

Note: custom adapters may return a Promise, so the previous example becomes:

  1. await socket.join("room1");
  2. io.to("room1").emit("hello");

Socket.use() is removed

socket.use() could be used as a catch-all listener. But its API was not really intuitive. It is replaced by socket.onAny().

UPDATE: the Socket.use() method was restored in socket.io@3.0.5.

Before:

  1. socket.use((packet, next) => {
  2. console.log(packet.data);
  3. next();
  4. });

After:

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

A middleware error will now emit an Error object

The error event is renamed to connect_error and the object emitted is now an actual Error:

Before:

  1. // server-side
  2. io.use((socket, next) => {
  3. next(new Error("not authorized"));
  4. });
  5. // client-side
  6. socket.on("error", err => {
  7. console.log(err); // not authorized
  8. });
  9. // or with an object
  10. // server-side
  11. io.use((socket, next) => {
  12. const err = new Error("not authorized");
  13. err.data = { content: "Please retry later" }; // additional details
  14. next(err);
  15. });
  16. // client-side
  17. socket.on("error", err => {
  18. console.log(err); // { content: "Please retry later" }
  19. });

After:

  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. });

Add a clear distinction between the Manager query option and the Socket query option

In previous versions, the query option was used in two distinct places:

  • in the query parameters of the HTTP requests (GET /socket.io/?EIO=3&abc=def)
  • in the CONNECT packet

Let’s take the following example:

  1. const socket = io({
  2. query: {
  3. token: "abc"
  4. }
  5. });

Under the hood, here’s what happened in the io() method:

  1. const { Manager } = require("socket.io-client");
  2. // a new Manager is created (which will manage the low-level connection)
  3. const manager = new Manager({
  4. query: { // sent in the query parameters
  5. token: "abc"
  6. }
  7. });
  8. // and then a Socket instance is created for the namespace (here, the main namespace, "/")
  9. const socket = manager.socket("/", {
  10. query: { // sent in the CONNECT packet
  11. token: "abc"
  12. }
  13. });

This behavior could lead to weird behaviors, for example when the Manager was reused for another namespace (multiplexing):

  1. // client-side
  2. const socket1 = io({
  3. query: {
  4. token: "abc"
  5. }
  6. });
  7. const socket2 = io("/my-namespace", {
  8. query: {
  9. token: "def"
  10. }
  11. });
  12. // server-side
  13. io.on("connection", (socket) => {
  14. console.log(socket.handshake.query.token); // abc (ok!)
  15. });
  16. io.of("/my-namespace").on("connection", (socket) => {
  17. console.log(socket.handshake.query.token); // abc (what?)
  18. });

That’s why the query option of the Socket instance is renamed to auth in Socket.IO v3:

  1. // plain object
  2. const socket = io({
  3. auth: {
  4. token: "abc"
  5. }
  6. });
  7. // or with a function
  8. const socket = io({
  9. auth: (cb) => {
  10. cb({
  11. token: "abc"
  12. });
  13. }
  14. });
  15. // server-side
  16. io.on("connection", (socket) => {
  17. console.log(socket.handshake.auth.token); // abc
  18. });

Note: the query option of the Manager can still be used in order to add a specific query parameter to the HTTP requests.

The Socket instance will no longer forward the events emitted by its Manager

In previous versions, the Socket instance emitted the events related to the state of the underlying connection. This will not be the case anymore.

You can still have access to those events on the Manager instance (the io property of the socket) :

Before:

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

After:

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

Here is the updated list of events emitted by the Manager:

NameDescriptionPreviously (if different)
opensuccessful (re)connection-
error(re)connection failure or error after a successful connectionconnect_error
closedisconnection-
pingping packet-
packetdata packet-
reconnect_attemptreconnection attemptreconnect_attempt & reconnecting
reconnectsuccessful reconnection-
reconnect_errorreconnection failure-
reconnect_failedreconnection failure after all attempts-

Here is the updated list of events emitted by the Socket:

NameDescriptionPreviously (if different)
connectsuccessful connection to a Namespace-
connect_errorconnection failureerror
disconnectdisconnection-

And finally, here’s the updated list of reserved events that you cannot use in your application:

  • connect (used on the client-side)
  • connect_error (used on the client-side)
  • disconnect (used on both sides)
  • disconnecting (used on the server-side)
  • newListener and removeListener (EventEmitter reserved events)
  1. socket.emit("connect_error"); // will now throw an Error

Namespace.clients() is renamed to Namespace.allSockets() and now returns a Promise

This function returns the list of socket IDs that are connected to this namespace.

Before:

  1. // all sockets in default namespace
  2. io.clients((error, clients) => {
  3. console.log(clients); // => [6em3d4TJP8Et9EMNAAAA, G5p55dHhGgUnLUctAAAB]
  4. });
  5. // all sockets in the "chat" namespace
  6. io.of("/chat").clients((error, clients) => {
  7. console.log(clients); // => [PZDoMHjiu8PYfRiKAAAF, Anw2LatarvGVVXEIAAAD]
  8. });
  9. // all sockets in the "chat" namespace and in the "general" room
  10. io.of("/chat").in("general").clients((error, clients) => {
  11. console.log(clients); // => [Anw2LatarvGVVXEIAAAD]
  12. });

After:

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

Note: this function was (and still is) supported by the Redis adapter, which means that it will return the list of socket IDs across all the Socket.IO servers.

Client bundles

There are now 3 distinct bundles:

NameSizeDescription
socket.io.js34.7 kB gzipUnminified version, with debug
socket.io.min.js14.7 kB min+gzipProduction version, without debug
socket.io.msgpack.min.js15.3 kB min+gzipProduction version, without debug and with the msgpack parser

By default, all of them are served by the server, at /socket.io/<name>.

Before:

  1. <!-- note: this bundle was actually minified but included the debug package -->
  2. <script src="/socket.io/socket.io.js"></script>

After:

  1. <!-- during development -->
  2. <script src="/socket.io/socket.io.js"></script>
  3. <!-- for production -->
  4. <script src="/socket.io/socket.io.min.js"></script>

No more “pong” event for retrieving latency

In Socket.IO v2, you could listen to the pong event on the client-side, which included the duration of the last health check round-trip.

Due to the reversal of the heartbeat mechanism (more information here), this event has been removed.

Before:

  1. socket.on("pong", (latency) => {
  2. console.log(latency);
  3. });

After:

  1. // server-side
  2. io.on("connection", (socket) => {
  3. socket.on("ping", (cb) => {
  4. if (typeof cb === "function")
  5. cb();
  6. });
  7. });
  8. // client-side
  9. setInterval(() => {
  10. const start = Date.now();
  11. // volatile, so the packet will be discarded if the socket is not connected
  12. socket.volatile.emit("ping", () => {
  13. const latency = Date.now() - start;
  14. // ...
  15. });
  16. }, 5000);

ES modules syntax

The ECMAScript modules syntax is now similar to the Typescript one (see below).

Before (using default import):

  1. // server-side
  2. import Server from "socket.io";
  3. const io = new Server(8080);
  4. // client-side
  5. import io from 'socket.io-client';
  6. const socket = io();

After (with named import):

  1. // server-side
  2. import { Server } from "socket.io";
  3. const io = new Server(8080);
  4. // client-side
  5. import { io } from 'socket.io-client';
  6. const socket = io();

emit() chains are not possible anymore

The emit() method now matches the EventEmitter.emit() method signature, and returns true instead of the current object.

Before:

  1. socket.emit("event1").emit("event2");

After:

  1. socket.emit("event1");
  2. socket.emit("event2");

Room names are not coerced to string anymore

We are now using Maps and Sets internally instead of plain objects, so the room names are not implicitly coerced to string anymore.

Before:

  1. // mixed types were possible
  2. socket.join(42);
  3. io.to("42").emit("hello");
  4. // also worked
  5. socket.join("42");
  6. io.to(42).emit("hello");

After:

  1. // one way
  2. socket.join("42");
  3. io.to("42").emit("hello");
  4. // or another
  5. socket.join(42);
  6. io.to(42).emit("hello");

New features

Some of those new features may be backported to the 2.4.x branch, depending on the feedback of the users.

Catch-all listeners

This feature is inspired from the EventEmitter2 library (which is not used directly in order not to increase the browser bundle size).

It is available for both the server and the client sides:

  1. // server
  2. io.on("connection", (socket) => {
  3. socket.onAny((event, ...args) => {});
  4. socket.prependAny((event, ...args) => {});
  5. socket.offAny(); // remove all listeners
  6. socket.offAny(listener);
  7. const listeners = socket.listenersAny();
  8. });
  9. // client
  10. const socket = io();
  11. socket.onAny((event, ...args) => {});
  12. socket.prependAny((event, ...args) => {});
  13. socket.offAny(); // remove all listeners
  14. socket.offAny(listener);
  15. const listeners = socket.listenersAny();

Volatile events (client)

A volatile event is an event that is allowed to be dropped if the low-level transport is not ready yet (for example when an HTTP POST request is already pending).

This feature was already available on the server-side. It might be useful on the client-side as well, for example when the socket is not connected (by default, packets are buffered until reconnection).

  1. socket.volatile.emit("volatile event", "might or might not be sent");

Official bundle with the msgpack parser

A bundle with the socket.io-msgpack-parser will now be provided (either on the CDN or served by the server at /socket.io/socket.io.msgpack.min.js).

Pros:

  • events with binary content are sent as 1 WebSocket frame (instead of 2+ with the default parser)
  • payloads with lots of numbers should be smaller

Cons:

  1. // server-side
  2. const io = require("socket.io")(httpServer, {
  3. parser: require("socket.io-msgpack-parser")
  4. });

No additional configuration is needed on the client-side.

Miscellaneous

The Socket.IO codebase has been rewritten to TypeScript

Which means npm i -D @types/socket.io should not be needed anymore.

Server:

  1. import { Server, Socket } from "socket.io";
  2. const io = new Server(8080);
  3. io.on("connection", (socket: Socket) => {
  4. console.log(`connect ${socket.id}`);
  5. socket.on("disconnect", () => {
  6. console.log(`disconnect ${socket.id}`);
  7. });
  8. });

Client:

  1. import { io } from "socket.io-client";
  2. const socket = io("/");
  3. socket.on("connect", () => {
  4. console.log(`connect ${socket.id}`);
  5. });

Plain javascript is obviously still fully supported.

Support for IE8 and Node.js 8 is officially dropped

IE8 is no longer testable on the Sauce Labs platform, and requires a lot of efforts for very few users (if any?), so we are dropping support for it.

Besides, Node.js 8 is now EOL. Please upgrade as soon as possible!

How to upgrade an existing production deployment

  • first, update the servers with allowEIO3 set to true (added in socket.io@3.1.0)
  1. const io = require("socket.io")({
  2. allowEIO3: true // false by default
  3. });

Note: If you are using the Redis adapter to broadcast packets between nodes, you must use socket.io-redis@5 with socket.io@2 and socket.io-redis@6 with socket.io@3. Please note that both versions are compatible, so you can update each server one by one (no big bang is needed).

  • then, update the clients

This step may actually take some time, as some clients may still have a v2 client in cache.

You can check the version of the connection with:

  1. io.on("connection", (socket) => {
  2. const version = socket.conn.protocol; // either 3 or 4
  3. });

This matches the value of the EIO query parameter in the HTTP requests.

  • and finally, once every client was updated, set allowEIO3 to false (which is the default value)
  1. const io = require("socket.io")({
  2. allowEIO3: false
  3. });

With allowEIO3 set to false, v2 clients will now receive an HTTP 400 error (Unsupported protocol version) when connecting.

Known migration issues

  • stream_1.pipeline is not a function
  1. TypeError: stream_1.pipeline is not a function
  2. at Function.sendFile (.../node_modules/socket.io/dist/index.js:249:26)
  3. at Server.serve (.../node_modules/socket.io/dist/index.js:225:16)
  4. at Server.srv.on (.../node_modules/socket.io/dist/index.js:186:22)
  5. at emitTwo (events.js:126:13)
  6. at Server.emit (events.js:214:7)
  7. at parserOnIncoming (_http_server.js:602:12)
  8. at HTTPParser.parserOnHeadersComplete (_http_common.js:116:23)

This error is probably due to your version of Node.js. The pipeline method was introduced in Node.js 10.0.0.

  • error TS2416: Property 'emit' in type 'Namespace' is not assignable to the same property in base type 'EventEmitter'.
  1. node_modules/socket.io/dist/namespace.d.ts(89,5): error TS2416: Property 'emit' in type 'Namespace' is not assignable to the same property in base type 'EventEmitter'.
  2. Type '(ev: string, ...args: any[]) => Namespace' is not assignable to type '(event: string | symbol, ...args: any[]) => boolean'.
  3. Type 'Namespace' is not assignable to type 'boolean'.
  4. node_modules/socket.io/dist/socket.d.ts(84,5): error TS2416: Property 'emit' in type 'Socket' is not assignable to the same property in base type 'EventEmitter'.
  5. Type '(ev: string, ...args: any[]) => this' is not assignable to type '(event: string | symbol, ...args: any[]) => boolean'.
  6. Type 'this' is not assignable to type 'boolean'.
  7. Type 'Socket' is not assignable to type 'boolean'.

The signature of the emit() method was fixed in version 3.0.1 (commit).

  • the client is disconnected when sending a big payload (> 1MB)

This is probably due to the fact that the default value of maxHttpBufferSize is now 1MB. When receiving a packet that is larger than this, the server disconnects the client, in order to prevent malicious clients from overloading the server.

You can adjust the value when creating the server:

  1. const io = require("socket.io")(httpServer, {
  2. maxHttpBufferSize: 1e8
  3. });
  • Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at xxx/socket.io/?EIO=4&transport=polling&t=NMnp2WI. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

Since Socket.IO v3, you need to explicitly enable Cross-Origin Resource Sharing (CORS). The documentation can be found here.

  • Uncaught TypeError: packet.data is undefined

It seems that you are using a v3 client to connect to a v2 server, which is not possible. Please see the following section.

  • Object literal may only specify known properties, and 'extraHeaders' does not exist in type 'ConnectOpts'

Since the codebase has been rewritten to TypeScript (more information here), @types/socket.io-client is no longer needed and will actually conflict with the typings coming from the socket.io-client package.