Server Initialization

    ES modules

    Please see for enabling ECMAScript modules in your Node.js project.

    1. import { createServer } from "http";
      import { Server } from "socket.io";

      const httpServer = createServer();
      const io = new Server(httpServer, {
      // ...
      });

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

      httpServer.listen(3000);

    TypeScript

    Socket.IO has now first-class support for TypeScript:

    1. import { createServer } from "http";
      import { Server, Socket } from "socket.io";

      const httpServer = createServer();
      const io = new Server(httpServer, {
      // ...
      });

      io.on("connection", (socket: Socket) => {
      // ...
      });

      httpServer.listen(3000);
    1. const options = { /* ... */ };
      const io = require("socket.io")(options);

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

      io.listen(3000);

    You can also pass the port as the first argument:

    1. const options = { /* ... */ };
      const io = require("socket.io")(3000, options);

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

    This implicitly starts a Node.js , which can be accessed through io.httpServer.

    Attached to an existing HTTP server

    With an HTTP server

    1. const httpServer = require("http").createServer();
      const options = { /* ... */ };
      const io = require("socket.io")(httpServer, options);

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

      httpServer.listen(3000);

    With an HTTPS server

    1. const fs = require("fs");
      const httpServer = require("https").createServer({
      key: fs.readFileSync("/tmp/key.pem"),
      cert: fs.readFileSync("/tmp/cert.pem")
      });
      const options = { /* ... */ };
      const io = require("socket.io")(httpServer, options);

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

      httpServer.listen(3000);

    With an HTTP/2 server

    1. const fs = require("fs");
      const httpServer = require("http2").createSecureServer({
      allowHTTP1: true,
      key: fs.readFileSync("/tmp/key.pem"),
      cert: fs.readFileSync("/tmp/cert.pem")
      });
      const options = { /* ... */ };
      const io = require("socket.io")(httpServer, options);

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

      httpServer.listen(3000);

    With Express

    More information .

    1. const app = require("koa")();
      const httpServer = require("http").createServer(app.callback());
      const options = { /* ... */ };
      const io = require("socket.io")(httpServer, options);

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

      httpServer.listen(3000);

    More information here.

    With Nest

    See the documentation here.

    Note: NestJS v7 and below relies on Socket.IO v2, while NestJS v8 relies on Socket.IO v4. Please use a .

    With Fastify

    You need to register the plugin:

    1. const app = require("fastify")();

      app.register(require("fastify-socket.io"));

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

      app.listen(3000);

    path

    Default value: /socket.io/

    It is the name of the path that is captured on the server side.

    The server and the client values must match (unless you are using a path-rewriting proxy in between):

    Server

    1. const httpServer = require("http").createServer();
      const io = require("socket.io")(httpServer, {
      path: "/my-custom-path/"
      });

    Client

    serveClient

    Default value: true

    Whether to serve the client files. If true, the different bundles will be served at the following location:

    • <url>/socket.io/socket.io.js
    • <url>/socket.io/socket.io.min.js
    • <url>/socket.io/socket.io.msgpack.min.js

    (including their associated source maps)

    See also .

    adapter

    Default value: socket.io-adapter (in-memory adapter, whose source code can be found )

    The “Adapter” to use.

    Example with the Redis adapter (the socket.io-redis package, more information ):

    1. const httpServer = require("http").createServer();
      const redisClient = require("redis").createClient();
      const io = require("socket.io")(httpServer, {
      adapter: require("socket.io-redis")({
      pubClient: redisClient,
      subClient: redisClient.duplicate()
      })
      });

    parser

    Default value: socket.io-parser

    connectTimeout

    Default value: 45000

    The number of ms before disconnecting a client that has not successfully joined a namespace.

    Low-level engine options

    pingTimeout

    Default value: 20000

    This value is used in the heartbeat mechanism, which periodically checks if the connection is still alive between the server and the client.

    The server sends a ping, and if the client does not answer with a pong within pingTimeout ms, the server considers that the connection is closed.

    Similarly, if the client does not receive a ping from the server within pingInterval + pingTimeout ms, the client also considers that the connection is closed.

    In both cases, the disconnection reason will be: ping timeout

    1. socket.on("disconnect", (reason) => {
      console.log(reason); // "ping timeout"
      });

    Note: the default value might be a bit low if you need to send big files in your application. Please increase it if that’s the case:

    1. const io = require("socket.io")(httpServer, {
      pingTimeout: 30000
      });

    pingInterval

    Default value: 25000

    See .

    upgradeTimeout

    Default value: 10000

    This is the delay in milliseconds before an uncompleted transport upgrade is cancelled.

    maxHttpBufferSize

    Default value: 1e6 (1 MB)

    This defines how many bytes a single message can be, before closing the socket. You may increase or decrease this value depending on your needs.

    It matches the maxPayload option of the ws package.

    allowRequest

    Default: -

    A function that receives a given handshake or upgrade request as its first parameter, and can decide whether to continue or not.

    Example:

    1. const io = require("socket.io")(httpServer, {
      allowRequest: (req, callback) => {
      const isOriginValid = check(req);
      callback(null, isOriginValid);
      }
      });

    transports

    Default value:

    The low-level transports that are allowed on the server-side.

    See also: client-side

    allowUpgrades

    Default value: true

    Whether to allow transport upgrades.

    perMessageDeflate

    History

    Whether to enable the permessage-deflate extension for the WebSocket transport. This extension is known to add a significant overhead in terms of performance and memory consumption, so we suggest to only enable it if it is really needed.

    Please note that if perMessageDeflate is set to false (which is the default), the compress flag used when emitting (socket.compress(true).emit(...)) will be ignored when the connection is established with WebSockets, as the permessage-deflate extension cannot be enabled on a per-message basis.

    All options from the are supported:

    1. const io = require("socket.io")(httpServer, {
      perMessageDeflate: {
      threshold: 2048, // defaults to 1024

      zlibDeflateOptions: {
      chunkSize: 8 * 1024, // defaults to 16 * 1024
      },

      zlibInflateOptions: {
      windowBits: 14, // defaults to 15
      memLevel: 7, // defaults to 8
      },

      clientNoContextTakeover: true, // defaults to negotiated value.
      serverNoContextTakeover: true, // defaults to negotiated value.
      serverMaxWindowBits: 10, // defaults to negotiated value.

      concurrencyLimit: 20, // defaults to 10
      }
      });

    httpCompression

    Added in v1.4.0

    Default value: true

    Whether to enable the compression for the HTTP long-polling transport.

    Please note that if httpCompression is set to false, the compress flag used when emitting (socket.compress(true).emit(...)) will be ignored when the connection is established with HTTP long-polling requests.

    All options from the Node.js are supported.

    Example:

    1. const io = require("socket.io")(httpServer, {
      httpCompression: {
      // Engine.IO options
      threshold: 2048, // defaults to 1024
      // Node.js zlib options
      chunkSize: 8 * 1024, // defaults to 16 * 1024
      windowBits: 14, // defaults to 15
      memLevel: 7, // defaults to 8
      }
      });

    wsEngine

    Default value: "ws" (source code can be found )

    The WebSocket server implementation to use. Please see the documentation here.

    Example:

    1. const io = require("socket.io")(httpServer, {
      wsEngine: require("eiows").Server
      });

    cors

    Default value: -

    The list of options that will be forwarded to the cors module. More information can be found .

    Example:

    1. const io = require("socket.io")(httpServer, {
      cors: {
      origin: ["https://example.com", "https://dev.example.com"],
      allowedHeaders: ["my-custom-header"],
      credentials: true
      }
      });

    Default value: -

    The list of options that will be forwarded to the module.

    Please note that since Socket.IO v3, there is no cookie sent by default anymore (reference).

    Example:

    1. const io = require("socket.io")(httpServer, {
      cookie: {
      name: "my-cookie",
      httpOnly: true,
      sameSite: "strict",
      maxAge: 86400
      }
      });

    allowEIO3

    Default value: false

    Whether to enable compatibility with Socket.IO v2 clients.

    See also: Migrating from 2.x to 3.0

    Example:

      Caught a mistake? Edit this page on