# JavaScript WebSocket libraries

JavaScript WebSocket libraries keep one connection open between a server and its clients, and either side can send a message over it at any time. These libraries let chat apps, live dashboards, and AI agents push updates to clients as they happen, without the client polling the server.

## Popularity

| Library | Monthly downloads | Stars | Last release | License |
| --- | --- | --- | --- | --- |
| [ws](#ws) | 1.5B | 22.8K | Nov 2026 | MIT |
| [faye-websocket](#faye-websocket) | 156.8M | 612 | Nov 2026 | Apache-2.0 |
| [websocket-driver](#websocket-driver) | 155.4M | 111 | Nov 2026 | Apache-2.0 |
| [crossws](#crossws) | 129.6M | 745 | Oct 2026 | MIT |
| [Socket.IO](#socket-io) | 100.0M | 63.3K | Sep 2026 | MIT |
| [Engine.IO](#engine-io) | 97.4M | 63.3K | Sep 2026 | MIT |
| [SockJS](#sockjs-node) | 65.9M | 2.1K | Dec 2021 | MIT |
| [graphql-ws](#graphql-ws) | 63.9M | 1.9K | Nov 2026 | MIT |

Downloads: npm, last thirty days. Stars and releases: GitHub. Amber: no release in over a year.

[ws](#ws) has the most monthly downloads in this comparison, at 1.5B.

## Capabilities

| Library | Binary application payloads | HTTP long-polling transport |
| --- | --- | --- |
| [ws](#ws) | Yes | No |
| [faye-websocket](#faye-websocket) | Yes | No |
| [websocket-driver](#websocket-driver) | Yes | No |
| [crossws](#crossws) | Yes | No |
| [Socket.IO](#socket-io) | Yes | Yes |
| [Engine.IO](#engine-io) | Yes | Yes |
| [SockJS](#sockjs-node) | No | Yes |
| [graphql-ws](#graphql-ws) | No | No |

## Libraries

### ws

[GitHub](https://github.com/websockets/ws) · [npm](https://www.npmjs.com/package/ws) · [Docs](https://api.github.com/repos/websockets/ws/contents/doc/ws.md)

ws implements WebSocket clients and servers for Node.js and passes the Autobahn protocol test suite. A `WebSocketServer` listens on its own port or shares an existing HTTP server, and each connection emits a `message` event and sends with `send`, for text or binary data. The library runs only in Node.js: in the browser, the built-in `WebSocket` object connects to a ws server directly. Compression through the permessage-deflate extension is off by default on the server, because it costs speed and memory.

- Downloads / mo: 1.5B
- Stars: 22.8K
- Last release: 8.23.0
- License: MIT
- Capabilities: [From the ws docs](https://api.github.com/repos/websockets/ws/contents/doc/ws.md)

**Strengths**

- **Works with standard WebSocket clients.** Browsers connect with their built-in WebSocket object.
- **Shares an existing HTTP server.** Handles WebSocket upgrades on the same HTTP server as the app.

**Watch out for**

- **Browser clients need another API.** In the browser, the native WebSocket object takes its place.
- **Compression adds memory overhead.** The permessage-deflate extension costs speed and memory, so it's off by default on the server.

```sh
npm install ws@8.23.0
```

**prisma/prisma-examples** (6.7K stars)

[prisma/prisma-examples](https://github.com/prisma/prisma-examples) 

```javascript
async function start() {
  /** Create WS Server */
  const wsServer = new WebSocketServer({
    server: httpServer,
    path: '/graphql',
  })

  /** hand-in created schema and have the WS Server start listening */
  const serverCleanup = useServer({ schema, context }, wsServer)

  const server = new ApolloServer<Context>({
    schema,
    plugins: [
      ApolloServerPluginDrainHttpServer({ httpServer }),
      {
        async serverWillStart() {
          return {
            async drainServer() {
              await serverCleanup.dispose()
            },
          }
        },
      },
    ],
  })

  await server.start()
  app.use('/graphql', cors<cors.CorsRequest>(), express.json(), expressMiddleware(server, { context: async () => context }));

  httpServer.listen(PORT, () => {
    console.log(`🚀 Server ready at http://localhost:${PORT}/graphql`)
    console.log(`⏰ Subscriptions ready at http://localhost:${PORT}/graphql`)
    console.log(
      `⭐️ See sample queries: http://pris.ly/e/ts/graphql-subscriptions#using-the-graphql-api`,
    )
  })
}

```

[orm/graphql-subscriptions/src/server.ts](https://github.com/prisma/prisma-examples/blob/45d6bf6193c66bc869240df90c75b2e4b45d008f/orm/graphql-subscriptions/src/server.ts) · [More projects using ws →](https://dashboard.exa.ai/playground/search?q=Projects%20using%20ws%20for%20WebSocket%20communication&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```javascript
import { WebSocketServer } from "ws";
const server = new WebSocketServer({ port: 8080 });
server.on("connection", (socket) => socket.send("Hello"));

```

From [README.md](https://registry.npmjs.org/ws/latest)

### faye-websocket

[GitHub](https://github.com/faye/faye-websocket-node) · [npm](https://www.npmjs.com/package/faye-websocket) · [Docs](https://registry.npmjs.org/faye-websocket/latest)

faye-websocket handles WebSocket connections inside an existing Node.js HTTP server, using the same API that browsers expose. The app listens for the server's `upgrade` event, checks the request with `WebSocket.isWebSocket`, and creates a socket that emits `message` and `close` events and sends with `send`. The package also includes a WebSocket client and an `EventSource` handler for one-way server push over plain HTTP. It came out of the Faye messaging project and contains no server of its own.

- Downloads / mo: 156.8M
- Stars: 612
- Last release: 0.12.0
- License: Apache-2.0
- Capabilities: [From the faye-websocket docs](https://registry.npmjs.org/faye-websocket/latest)

**Strengths**

- **Standard WebSocket API.** Sockets expose the same send, message, and close interface as the browser's WebSocket.
- **Handles EventSource too.** One-way EventSource streams push data to clients over plain HTTP.

**Watch out for**

- **No server of its own.** The app's HTTP server passes each upgrade request to the library.

```sh
npm install faye-websocket@0.12.0
```

**faye/faye** (4.4K stars)

[faye/faye](https://github.com/faye/faye) 

```javascript
function(request, socket, head) {
    var options  = { maxLength: this._getMaxLength(), extensions: this._extensions, ping: this._options.ping },
        ws       = new WebSocket(request, socket, head, [], options),
        clientId = null,
        self     = this;

    request.originalUrl = request.url;

    ws.onmessage = function(event) {
      try {
        self.debug('Received message via WebSocket[' + ws.version + ']: ?', event.data);

        var message = self._parseJSON(event.data),
            cid     = idFromMessages(message);

        if (clientId && cid && cid !== clientId) self._server.closeSocket(clientId, false);
        self._server.openSocket(cid, ws, request);
        if (cid) clientId = cid;

        self._server.process(message, request, function(replies) {
          if (ws) ws.send(toJSON(replies));
        });
      } catch (error) {
        console.log(error.stack);
        self.error(error.message + '\nBacktrace:\n' + error.stack);
      }
    };

    ws.onclose = function(event) {
      self._server.closeSocket(clientId);
      ws = null;
    };
  }

```

[src/adapters/node_adapter.js](https://github.com/faye/faye/blob/96df432613dca46baa6e4ed78dadda775c6c46ee/src/adapters/node_adapter.js) · [More projects using faye-websocket →](https://dashboard.exa.ai/playground/search?q=faye-websocket%20GitHub%20projects)

**Quickstart**

```javascript
const http = require("node:http");
const WebSocket = require("faye-websocket");
const server = http.createServer();
server.on("upgrade", (request, socket, head) => {
  if (!WebSocket.isWebSocket(request)) return socket.destroy();
  const connection = new WebSocket(request, socket, head);
  connection.send("Hello");
});
server.listen(8080);

```

From [README.md](https://registry.npmjs.org/faye-websocket/latest)

### websocket-driver

[GitHub](https://github.com/faye/websocket-driver-node) · [npm](https://www.npmjs.com/package/websocket-driver) · [Docs](https://registry.npmjs.org/websocket-driver/latest)

websocket-driver implements the WebSocket protocol without doing any input or output itself, so it runs over any stream the app supplies. The driver selects the right protocol version for each client, performs the opening and closing handshakes, recombines fragmented messages, and answers ping frames with pongs. The app pipes bytes from a TCP socket or HTTP upgrade into the driver and writes the bytes it produces back out. faye-websocket is built on top of it.

- Downloads / mo: 155.4M
- Stars: 111
- Last release: 0.8.0
- License: Apache-2.0
- Capabilities: [From the websocket-driver docs](https://registry.npmjs.org/websocket-driver/latest)

**Strengths**

- **Works over any stream.** The app moves bytes in and out, and the driver handles the protocol.
- **Answers pings itself.** Replies to ping frames, recombines fragments, and runs the closing handshake.

```sh
npm install websocket-driver@0.8.0
```

**faye/faye-websocket-node** (612 stars)

[faye/faye-websocket-node](https://github.com/faye/faye-websocket-node) 

```javascript
var WebSocket = function(request, socket, body, protocols, options) {
  options = options || {};

  this._stream = socket;

  this._driver = driver.http(request, {
    maxLength: options.maxLength,
    protocols: protocols,
    allowDrafts: options.allowDrafts
  });

  var self = this;
  if (!this._stream || !this._stream.writable) return;
  if (!this._stream.readable) return this._stream.end();

  var catchup = function() { self._stream.removeListener('data', catchup) };
  this._stream.on('data', catchup);

  API.call(this, options);

  process.nextTick(function() {
    self._driver.start();
    self._driver.io.write(body);
  });
};

```

[lib/faye/websocket.js](https://github.com/faye/faye-websocket-node/blob/35243279ea1f759cf68fe99229b326145ad3513d/lib/faye/websocket.js) · [More projects using websocket-driver →](https://dashboard.exa.ai/playground/search?q=websocket-driver%20GitHub%20projects)

**Quickstart**

```javascript
const http = require("node:http");
const websocket = require("websocket-driver");
const server = http.createServer();
server.on("upgrade", (request, socket, head) => {
  if (!websocket.isWebSocket(request)) return socket.destroy();
  const driver = websocket.http(request);
  driver.io.write(head);
  socket.pipe(driver.io).pipe(socket);
  driver.start();
  driver.text("Hello");
});
server.listen(8080);

```

From [README.md](https://registry.npmjs.org/websocket-driver/latest)

### crossws

[GitHub](https://github.com/h3js/crossws) · [npm](https://www.npmjs.com/package/crossws) · [Docs](https://crossws.h3.dev/adapters/node)

crossws defines one set of WebSocket server hooks, such as `open`, `message`, and `close`, and runs them on Node.js, Bun, Deno, and Cloudflare Workers through an adapter for each runtime. Each hook receives a `peer` object that sends messages and can subscribe to topics for publish and subscribe. The Node.js adapter ships with ws built in, and a separate adapter uses uWebSockets.

- Downloads / mo: 129.6M
- Stars: 745
- Last release: 0.4.17
- License: MIT
- Capabilities: [From the crossws docs](https://crossws.h3.dev/adapters/node)

**Strengths**

- **One API on four runtimes.** The same hooks run on Node.js, Bun, Deno, and Cloudflare Workers through adapters.
- **Bundles ws for Node.js.** The Node.js adapter ships with ws, and a uWebSockets adapter is also available.

```sh
npm install crossws@0.4.17
```

**nitrojs/nitro** (11.4K stars)

[nitrojs/nitro](https://github.com/nitrojs/nitro) 

```javascript
message(peer, message) {
    if (message.text().includes("ping")) {
      peer.send({ user: "server", message: "pong" });
    } else {
      const msg = {
        user: peer.toString(),
        message: message.toString(),
      };
      peer.send(msg); // echo
      peer.publish("chat", msg);
    }
  }

```

[examples/websocket/routes/_ws.ts](https://github.com/nitrojs/nitro/blob/749b12bc82dfa75ef99c9a4b0d33b2278d7aa4b8/examples/websocket/routes/_ws.ts) · [More projects using crossws →](https://dashboard.exa.ai/playground/search?q=crossws%20GitHub%20projects)

**Quickstart**

```javascript
import { createServer } from "node:http";
import crossws from "crossws/adapters/node";
const adapter = crossws({ hooks: { open(peer) { peer.send("Hello"); } } });
const server = createServer((request, response) => response.end("WebSocket server"));
server.on("upgrade", (request, socket, head) => adapter.handleUpgrade(request, socket, head));
server.listen(8080);

```

From [node.md](https://registry.npmjs.org/crossws/latest)

### Socket.IO

[GitHub](https://github.com/socketio/socket.io) · [npm](https://www.npmjs.com/package/socket.io) · [Docs](https://registry.npmjs.org/socket.io/latest)

Socket.IO sends named events between a server and its clients, such as `socket.emit('hello', 'world')`, with optional acknowledgements that work like callbacks. A connection starts over HTTP long-polling and upgrades to WebSocket when the network allows it. Sockets can join rooms, and a broadcast to a room reaches every socket in it. Socket.IO uses its own protocol on top of WebSocket, so browsers connect with the Socket.IO client library rather than the built-in `WebSocket` object.

- Downloads / mo: 100.0M
- Stars: 63.3K
- Last release: 4.8.4
- License: MIT
- Capabilities: [From the Socket.IO docs](https://registry.npmjs.org/socket.io/latest)

**Strengths**

- **Falls back to HTTP polling.** Event connections keep working when a network blocks WebSocket.
- **Broadcasts to selected groups.** Rooms send events to a chosen group of connected clients.

**Watch out for**

- **Requires a Socket.IO client.** A plain WebSocket client cannot connect to a Socket.IO server.
- **Missed events need application storage.** Server events sent during a disconnect are lost unless the app stores them.

```sh
npm install socket.io@4.8.4
```

**nestjs/nest** (77.1K stars)

[nestjs/nest](https://github.com/nestjs/nest) 

```javascript
public createIOServer(
  port: number | undefined,
  options?: ServerOptions,
): Server {
  if (this.httpServer && port === 0) {
    return new Server(this.httpServer, options);
  }
  return new Server(port, options);
}

```

[packages/platform-socket.io/adapters/io-adapter.ts](https://github.com/nestjs/nest/blob/09b656cb8df02a5f6ae1d0c5f1a0f2fadf7bc43c/packages/platform-socket.io/adapters/io-adapter.ts) · [More projects using Socket.IO →](https://dashboard.exa.ai/playground/search?q=Projects%20using%20socket.io%20for%20WebSocket%20communication&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```javascript
import { Server } from "socket.io";
const server = new Server(3000);
server.on("connection", (socket) => socket.emit("hello", "world"));

```

From [README.md](https://registry.npmjs.org/socket.io/latest)

### Engine.IO

[GitHub](https://github.com/socketio/socket.io) · [npm](https://www.npmjs.com/package/engine.io) · [Docs](https://registry.npmjs.org/engine.io/latest)

Engine.IO is the transport layer underneath Socket.IO. It opens a two-way connection between a Node.js server and a client over HTTP long-polling first, then upgrades to WebSocket or WebTransport when possible. `engine.attach` adds it to an existing HTTP server, and each connection emits `message` events and sends with `send`. It has no rooms or named events, which Socket.IO adds on top, and its code now lives in the Socket.IO monorepo.

- Downloads / mo: 97.4M
- Stars: 63.3K
- Last release: 6.6.11
- License: MIT
- Capabilities: [From the Engine.IO docs](https://registry.npmjs.org/engine.io/latest)

**Strengths**

- **Starts on long-polling.** Connections open over HTTP, then upgrade to WebSocket or WebTransport when they can.

```sh
npm install engine.io@6.6.11
```

**primus/primus** (4.5K stars)

[primus/primus](https://github.com/primus/primus) 

```javascript
function server() {
  this.service = new engine.Server(Object.assign({
    perMessageDeflate: !!this.primus.options.compression,
    httpCompression: !!this.primus.options.compression,
    maxHttpBufferSize: this.primus.options.maxLength
  }, this.primus.options.transport));

  //
  // We've received a new connection, create a new Spark. The Spark will
  // automatically announce it self as a new connection once it's created (after
  // the next tick).
  //
  this.service.on('connection', (socket) => {
    const spark = new this.Spark(
        socket.request.headers  // HTTP request headers.
      , socket.request.primus   // IP Address location.
      , socket.request.query    // Optional query string.
      , socket.id               // Unique connection id.
      , socket.request          // Reference to the HTTP req.
      , socket                  // Reference to the Engine.IO socket.
    );

    spark.on('outgoing::end', () => socket && socket.close());
    spark.on('outgoing::data', (data) => socket.write(data));

    socket.on('error', spark.emits('incoming::error'));
    socket.on('data', spark.emits('incoming::data'));
    socket.on('close', spark.emits('incoming::end', (next) => {
      socket.removeAllListeners();
      socket = null;
      next();
    }));
  });

  //
  // Listen to upgrade requests.
  //
  this.on('upgrade', (req, socket, head) => {
    this.service.handleUpgrade(req, socket, head);
  }).on('request', (req, res) => {
    //
    // Engine.IO closes the handshake socket before we receive a `connection`
    // event. And as the socket is already answered it can be undefined.
    //
    req.primus = {
      remoteAddress: req.socket.remoteAddress,
      remotePort: req.socket.remotePort
    };

    this.service.handleRequest(req, res);
  }).once('close',  () => this.service.close());
}

```

[transformers/engine.io/server.js](https://github.com/primus/primus/blob/7158e36b361c473a915c7df51bfaab199fceeec3/transformers/engine.io/server.js#L12-L63) · [More projects using Engine.IO →](https://dashboard.exa.ai/playground/search?q=engine.io%20GitHub%20projects)

**Quickstart**

```javascript
const http = require("node:http");
const engine = require("engine.io");
const server = http.createServer();
const transport = engine.attach(server);
transport.on("connection", (socket) => socket.send("Hello"));
server.listen(8080);

```

From [README.md](https://registry.npmjs.org/engine.io/latest)

### SockJS

[GitHub](https://github.com/sockjs/sockjs-node) · [npm](https://www.npmjs.com/package/sockjs) · [Docs](https://registry.npmjs.org/sockjs/latest)

SockJS-node is the Node.js server for SockJS, a protocol that gives browsers a WebSocket-like object even where WebSocket is blocked. The SockJS client in the browser tries WebSocket first and falls back to HTTP streaming or polling. On the server, `sockjs.createServer` returns a server whose `installHandlers` call mounts it under a URL prefix on an existing HTTP server. Each connection emits `data` events and sends with `write`, which takes strings only.

- Downloads / mo: 65.9M
- Stars: 2.1K
- Last release: 0.3.24
- License: MIT
- Capabilities: [From the SockJS docs](https://registry.npmjs.org/sockjs/latest)

**Strengths**

- **Works without WebSocket transport.** The browser gets a WebSocket-like connection over fallback transports.
- **Shares an existing HTTP server.** Handlers install under a URL prefix next to other HTTP handlers.

**Watch out for**

- **Messages must be strings.** Structured or binary data has to be encoded as text before write.
- **Multiple servers need session affinity.** Every request in a session has to reach the same server.

```sh
npm install sockjs@0.3.24
```

**CodeboxIDE/codebox** (4.2K stars)

[CodeboxIDE/codebox](https://github.com/CodeboxIDE/codebox) 

```javascript
var init = function(server, config) {
    var socket = sockjs.createServer({
        log: logger.log.bind(logger)
    });

    socket.on('connection', function(conn) {
        var service = (conn.pathname.split("/"))[2];
        logger.log("connection to service '"+service+"'");

        if (!services[service]) {
            conn.close(404, "Service not found");
            return logger.error("invalid service '"+service+"'");
        }

        conn.do = function(method, data) {
            this.write(JSON.stringify({
                'method': method,
                'data': data
            }));
        }.bind(conn);

        conn.on("data", function(data) {
            try {
                data = JSON.parse(data);
            } catch(e) {
                logger.error("error parsing data:", data);
                return;
            }

            if (data.method) {
                conn.emit("do."+data.method, data.data || {});
            } else {
                conn.emit("message", data);
            }
        });

        services[service].handler(conn);
    });

    socket.installHandlers(server, {
        prefix: '^/socket/(\\w+)'
    });
};

```

[lib/socket.js](https://github.com/CodeboxIDE/codebox/blob/98b4710f1bdba615dddbab56011a86cd5f16897b/lib/socket.js) · [More projects using SockJS →](https://dashboard.exa.ai/playground/search?q=Projects%20using%20sockjs%20for%20WebSocket%20communication&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```javascript
var http = require('http');
var sockjs = require('sockjs');

var echo = sockjs.createServer();
echo.on('connection', function(conn) {
    conn.on('data', function(message) {
        conn.write(message);
    });
    conn.on('close', function() {});
});

var server = http.createServer();
echo.installHandlers(server, {prefix:'/echo'});
server.listen(9999, '0.0.0.0');

```

From [README.md](https://registry.npmjs.org/sockjs/latest)

### graphql-ws

[GitHub](https://github.com/enisdenjo/graphql-ws) · [npm](https://www.npmjs.com/package/graphql-ws) · [Docs](https://api.github.com/repos/enisdenjo/graphql-ws/contents/src/use/ws.ts)

graphql-ws implements the GraphQL over WebSocket Protocol, which carries GraphQL queries, mutations, and subscriptions over one WebSocket connection. On the server, `useServer` attaches a GraphQL schema to a ws server, and the client side calls `createClient` with the server's URL. The package has no dependencies. It is not compatible with the deprecated subscriptions-transport-ws protocol, so the server and every client have to use it.

- Downloads / mo: 63.9M
- Stars: 1.9K
- Last release: 6.4.3
- License: MIT
- Capabilities: [From the graphql-ws docs](https://api.github.com/repos/enisdenjo/graphql-ws/contents/src/use/ws.ts)

**Strengths**

- **No dependencies.** One package holds both the server and the client for the protocol.

**Watch out for**

- **Separate from the old protocol.** Clients built on subscriptions-transport-ws can't connect, so both sides have to switch.

```sh
npm install graphql-ws@6.4.3 ws@8.23.0 graphql@16
```

**prisma/prisma-examples** (6.7K stars)

[prisma/prisma-examples](https://github.com/prisma/prisma-examples) 

```javascript
async function start() {
  /** Create WS Server */
  const wsServer = new WebSocketServer({
    server: httpServer,
    path: '/graphql',
  })

  /** hand-in created schema and have the WS Server start listening */
  const serverCleanup = useServer({ schema, context }, wsServer)

  const server = new ApolloServer<Context>({
    schema,
    plugins: [
      ApolloServerPluginDrainHttpServer({ httpServer }),
      {
        async serverWillStart() {
          return {
            async drainServer() {
              await serverCleanup.dispose()
            },
          }
        },
      },
    ],
  })

  await server.start()
  app.use('/graphql', cors<cors.CorsRequest>(), express.json(), expressMiddleware(server, { context: async () => context }));

  httpServer.listen(PORT, () => {
    console.log(`🚀 Server ready at http://localhost:${PORT}/graphql`)
    console.log(`⏰ Subscriptions ready at http://localhost:${PORT}/graphql`)
    console.log(
      `⭐️ See sample queries: http://pris.ly/e/ts/graphql-subscriptions#using-the-graphql-api`,
    )
  })
}

```

[orm/graphql-subscriptions/src/server.ts](https://github.com/prisma/prisma-examples/blob/45d6bf6193c66bc869240df90c75b2e4b45d008f/orm/graphql-subscriptions/src/server.ts) · [More projects using graphql-ws →](https://dashboard.exa.ai/playground/search?q=graphql-ws%20GitHub%20projects)

**Quickstart**

```javascript
import { GraphQLObjectType, GraphQLSchema, GraphQLString } from "graphql";
import { WebSocketServer } from "ws";
import { useServer } from "graphql-ws/use/ws";
const schema = new GraphQLSchema({ query: new GraphQLObjectType({ name: "Query", fields: { hello: { type: GraphQLString, resolve: () => "Hello" } } }) });
useServer({ schema }, new WebSocketServer({ port: 4000 }));

```

From [ws.ts](https://registry.npmjs.org/graphql-ws/latest)

## FAQ

### Which JavaScript WebSocket library should I use?

For a plain WebSocket server in Node.js, use [ws](#ws), which browsers reach through their built-in `WebSocket` object. For rooms, broadcasts, and fallback to HTTP long-polling, use [Socket.IO](#socket-io) with its client library. For one server that runs on Node.js, Bun, Deno, and Cloudflare Workers, use [crossws](#crossws), and for GraphQL subscriptions, [graphql-ws](#graphql-ws).

### How do I create a WebSocket server in Node.js?

Install [ws](#ws), create a `WebSocketServer` on a port, and listen for its `connection` event. Each connection's `send` method writes a message, and its `message` event fires for every message the client sends.

### Socket.IO vs ws: which should I use?

ws implements the WebSocket protocol, so any WebSocket client can connect, including the browser's built-in one. Socket.IO adds its own protocol on top, with rooms, acknowledgements, and fallback to HTTP long-polling, and only a Socket.IO client can connect to its server.

### What is graphql-ws?

graphql-ws implements the GraphQL over WebSocket Protocol for both server and client, with no dependencies. It isn't compatible with the deprecated subscriptions-transport-ws package, so the server and the client both have to use it.

### SockJS vs Socket.IO: which should I use?

Both fall back to HTTP transports when WebSocket is unavailable. SockJS gives the browser a WebSocket-like object and sends text messages only. Socket.IO sends named events and adds rooms and acknowledgements.

### Does Socket.IO need sticky sessions?

Yes, while HTTP long-polling is on: every request in a session has to reach the server that started it. Turning long-polling off and using WebSocket only removes that requirement.

## How this page was built

Data checked Nov 19, 2026.

Reproduce it with the Exa API:

```json
{
  "endpoint": "/search",
  "body": {
    "query": "Best JavaScript WebSocket libraries ws Socket.IO SockJS WebSocket Node code examples",
    "numResults": 5
  }
}
```

Docs: https://exa.ai/docs/reference/search
