# ws — card for AI agents

Simple, fast WebSocket client and server for Node.js with full RFC support.

Category: HTTP clients and networking · npm package `ws` · latest version 8.22.1 (checked 2026-11-01)
Install: `npm install ws`
License: MIT (permissive)

In your own product (generator, app, hosted service): **yes**. Permissive license: ship it inside your own product, closed or open source, and keep its license and copyright notice.

## Rules for AI agents (paste into AGENTS.md or CLAUDE.md)

## ws
- Use ws only in Node.js code. Browser code must use the native `WebSocket` object.
- Register an `error` listener on each connection, as the README examples do (`ws.on('error', console.error)`).
- To serve several WebSocket endpoints or to authenticate on one HTTP server, create servers with `noServer: true`. Route or authenticate in the HTTP server's `upgrade` handler, then call `handleUpgrade` and emit `connection`.
- When broadcasting, send only to clients whose `readyState === WebSocket.OPEN`, and pass `{ binary: isBinary }` through.
- Keep `perMessageDeflate` at its server default (disabled) and enable it only if it is really needed. If you enable it, test memory and performance under a representative workload first.
- For broken-connection detection, follow the README heartbeat: mark clients alive on `pong`, `terminate()` ones that did not answer, and clear the interval on server `close`.
- Behind a proxy like NGINX, the README gives the `X-Forwarded-For` header as the de-facto standard for the client IP.

## What it is
- ws is a WebSocket library for Node.js. It has a server (`WebSocketServer`) and a client (`WebSocket`). The repository was created on 2011-11-09 and is MIT licensed. The GitHub repository description calls it a "simple to use, blazing fast and thoroughly tested WebSocket client and server for Node.js". HyBi drafts 13-17 are the default, and drafts 07-12 are available with `protocolVersion: 8`.
- It does not run in the browser. In the docs, "client" means a backend that plays the client role in a WebSocket connection. Browser code must use the native `WebSocket` object.
- The README shows three server setups. In the first, the server listens on its own port. In the second, it attaches to an existing HTTP/S server through the `server` option. In the third, it uses `noServer: true`: your HTTP server's `upgrade` handler decides what happens and then calls `handleUpgrade`. The README uses this third setup to put several WebSocket servers on one HTTP server and to reject unauthenticated requests before the handshake. The rest of the README covers permessage-deflate tuning, binary data, broadcasting, a duplex-stream wrapper, and a ping/pong heartbeat for finding broken connections.

## Caveats
- Node.js only: Browser clients must use the native `WebSocket`. For code that runs in both places, the README points to wrappers on npm such as `isomorphic-ws`.
- Different compression defaults per side: permessage-deflate is off by default on the server and on by default on the client. The README says it adds "significant overhead", and the maintainers write that they suggest enabling it "only if it is really needed".
- zlib under concurrency: The README warns that Node.js compression can lead to "catastrophic memory fragmentation" and slow performance with more concurrency, especially on Linux. It advises a workload-representative test before using compression in production.
- Broken links can look open: The README says an interrupted link can leave both ends unaware that the connection is broken. Its answer is a ping-based heartbeat that you write on the server. It also suggests a ping listener on clients.
- Shared machines and optional modules: The README says forcing ws not to use `bufferutil` through `WS_NO_BUFFER_UTIL` can help security. This applies on systems where one user can place a package in another user's search path.

## Numbers (AgentGid data)
- Gid Score: 82.4 (#64 of all tools, 4 of 126 in its category)
- Used in 204 public projects set up for AI coding agents (3.3%)
- Downloads last week: 427,109,592 (as of 2026-11-24), +44.5% over 4 weeks
- GitHub stars: 22,838 (as of 2026-11-24)
- Last push: 2026-11-16

## Often used with
tsx 57.4%, dotenv 52.5%, Zod 64.7%, Express 41.2%, Vitest 58.3%, TypeScript 85.8%

## Checked alternatives (same job)
- Socket.IO Client: https://agentgid.com/tools/socket-io-client/agent.md
- Socket.IO: https://agentgid.com/tools/socket-io/agent.md

## Links
- AgentGid page: https://agentgid.com/tools/ws/
- Homepage: https://github.com/websockets/ws
- Repository: https://github.com/websockets/ws
- Source: https://github.com/websockets/ws#readme
- Source: https://github.com/websockets/ws
- Source: https://github.com/websockets/ws/releases


## ws: live two-way connections for Node.js servers

ws is a free library for Node.js that keeps a live, two-way connection open between your server and each visitor. The server can push new chat messages, prices or progress updates the moment they happen, without the page asking again. It runs only on the server side; the browser uses its own built-in WebSocket.

### Where to use it
- Live chat or comments: A message one visitor sends shows up for everyone else on the page at once, without reloading.
- Push updates from your server: Your Node.js server sends new orders, scores or job progress to the open page the moment they change.
- Listen to a live data feed: A backend script connects to another service's live feed, such as market prices or events, and reacts to each message.
- Let only signed-in users connect: Check the visitor's login before the live connection opens, and turn strangers away with "401 Unauthorized".
- Close dead connections: Find visitors whose phone lost signal or whose laptop went to sleep, and free the server's memory for them.
- Show an AI agent's progress live: While a long task runs on your server, send each step to the page so the person sees it moving instead of a spinner. (idea, not from the official pages)

### How to start
- Add ws to your Node.js project.

```
npm install ws
```

- Start a server that greets each new connection and logs what it receives.

```
import { WebSocketServer } from 'ws';
const wss = new WebSocketServer({ port: 8080 });
wss.on('connection', function connection(ws) {
  ws.on('error', console.error);
  ws.on('message', function message(data) {
    console.log('received: %s', data);
  });
  ws.send('something');
});
```

- In the browser, connect with the built-in WebSocket object, not with ws.

### License
Free to use, also in paid and closed-source products, under the MIT license. Keep its copyright and license notice in copies of the code you ship.

### Good to know
- It does not run in the browser. Web pages use the browser's own built-in WebSocket to talk to a ws server.
- By default one message may be as large as 100 MiB. Set a smaller limit for chats and forms so one visitor cannot fill the server's memory.
- Compression of messages is off on the server by default. The docs advise turning it on only when you really need it, because it costs speed and memory.
- The project is active. Version 8.22.2 came out on 2026-11-08, and two security fixes landed in May 2026 (8.20.1 and 8.21.0).

Checked 2026-11-10 against: https://github.com/websockets/ws/blob/master/README.md, https://github.com/websockets/ws/blob/master/doc/ws.md, https://github.com/websockets/ws/blob/master/LICENSE, https://github.com/websockets/ws/blob/master/package.json, https://github.com/websockets/ws/blob/master/SECURITY.md, https://github.com/websockets/ws/blob/master/browser.js, https://github.com/websockets/ws/blob/master/wrapper.mjs, https://github.com/websockets/ws/blob/master/index.js, https://github.com/websockets/ws/releases/tag/8.0.0, https://github.com/websockets/ws/releases/tag/8.22.2, https://registry.npmjs.org/ws

### Mistakes to avoid
- Don't: import WebSocket from 'ws'; new WebSocket.Server({ port: 8080 }) (from old CommonJS tutorials) → Do: import { WebSocketServer } from 'ws'; new WebSocketServer({ port: 8080 }) (WebSocket.Server is attached only in the CommonJS entry index.js; the ES module wrapper exports WebSocketServer as a named export and does not load index.js.)
- Don't: JSON.parse(data) or data === 'ping' in the 'message' handler, as in ws 7 code → Do: const text = isBinary ? data : data.toString(); then JSON.parse(text) (Since 8.0.0 text messages arrive as Buffers and the handler gets an isBinary flag.)
- Don't: import WebSocket from 'ws' in front-end code (React, Vue, plain pages) → Do: Use the browser's global WebSocket; keep ws on the server (ws is for Node.js only; its browser entry (browser.js) just throws an error telling you to use the native WebSocket.)
- Don't: Checking tokens with the verifyClient option → Do: Authenticate in server.on('upgrade') and call wss.handleUpgrade only for valid users (noServer mode) (The docs discourage verifyClient and show the upgrade-event pattern instead.)
- Don't: Leaving maxPayload at its default and pinning an old 8.x release → Do: Set maxPayload to what your messages need (for example 64 * 1024) and use 8.21.0 or newer (The default allows 100 MiB per message, and 8.20.1 and 8.21.0 fixed a memory disclosure bug and a memory exhaustion attack.)

### Questions
- Can I use ws in a React or plain browser page? No. In the browser use the built-in WebSocket object; ws is for Node.js servers and backend clients.
- How do I keep strangers out? Check the login in the HTTP server's 'upgrade' event and only then hand the connection to ws; the verifyClient option is discouraged.
- How do I notice that a visitor is gone? Send pings on a timer and terminate connections that did not answer with a pong since the last round.
- Can it share a port with my Express or HTTP server? Yes. Pass your server as the server option, or use noServer mode and route the 'upgrade' event yourself.
- Can I use it in a paid product? Yes, it is under the MIT license.

---
AgentGid's catalog is curated: every entry was checked against the maker's official pages (registry, repository, license and pricing pages) on the date shown; a license value shows the quote it stands on wherever AgentGid has one. Usage numbers come from AgentGid's own scan of public repositories set up for AI coding agents. Claims by makers are reported, not tested by AgentGid.
