The 'ws' Library: WebSockets for Node.js Servers
The ws library is the standard for adding WebSocket servers to Node.js for real-time features like chat or live data feeds. It provides both server and client APIs for backend-to-backend communication.
Why it exists
Node.js's core http module handles the request-response cycle, which is unsuitable for persistent, bidirectional communication. WebSockets were created for this real-time need, and the ws library provides a robust, high-performance, and widely adopted implementation for the Node.js ecosystem.
The mental model
Think of ws as the equivalent of Node's built-in http module, but for the WebSocket protocol (ws://). It gives you the low-level tools to create a WebSocketServer that listens for connections, and a WebSocket client to connect to other servers, all within a Node.js environment. It's the foundational layer for real-time communication on the backend.
How it works
After installing with npm install ws, you create a server by instantiating WebSocketServer and typically attaching it to an existing HTTP/S server. The server object emits a connection event for each new client. This event provides a client socket object with a send() method and a message event for sending and receiving data. The library handles the complex WebSocket handshake, protocol framing, and data masking, exposing a simple event-driven API. For maximum performance, you can optionally install binary addons like bufferutil.
When to use it
Use ws to build a WebSocket server in Node.js. This is ideal for applications requiring real-time updates: live chat, collaborative editing tools, real-time monitoring dashboards, and multiplayer game servers. You can also use its client component for backend services that need to consume a third-party WebSocket API.
When not to use it
The biggest mistake is trying to use ws in a web browser. Browsers have their own built-in WebSocket API for client-side connections; ws is strictly for Node.js environments. If you need higher-level features like automatic reconnection, rooms, or fallback transports, consider a framework like Socket.IO, which uses ws under the hood but adds more functionality.
One canonical example
A simple echo server that broadcasts every message it receives to all other connected clients:
const { WebSocketServer } = require('ws');
const wss = new WebSocketServer({ port: 8080 });wss.on('connection', function connection(ws) {
ws.on('message', function message(data) {
wss.clients.forEach(function each(client) {if (client !== ws && client.readyState === 1) { // 1 is WebSocket.OPEN
client.send(String(data));
}
});
});
});Interview question
What is the primary reason the 'ws' library is preferred over Node.js's built-in 'http' module for real-time applications?
- a.It automatically handles client-side reconnection logic and message broadcasting to rooms.
- b.It offers built-in support for HTTP/2 and server-sent events (SSE).
- c.It is designed for web browser clients, while 'http' is for server-to-server communication.
- d.It provides a persistent, bidirectional communication channel, unlike the request-response model.Correct
Why? this is the answer
The card explicitly states that Node.js's core 'http' module handles the 'request-response cycle, which is unsuitable for persistent, bidirectional communication,' and that 'WebSockets were created for this real-time need,' which 'ws' fulfills. The most tempting distractor, C, describes features provided by higher-level libraries like Socket.IO, not 'ws' itself.
Just read this? Test yourself on what you have been reading.
Read the original → github.com
- #nodejs
- #websockets
- #networking
- #backend
Put your scrolling time to good use
Learn one idea, try a quiz and save useful cards for revision. Tezvyn makes it easy to learn and stay current in your tech field, a few minutes at a time.
The iPhone app is on the way
We are building it. Until it lands, nothing here is held back from you: every interview card, your saved cards, streaks and the job board all work in Safari, plus hundreds of free practice quizzes of thirty questions each. Sign in and it all carries over to the app the day it arrives.
Want it as an icon? Tap Share at the bottom of Safari, then Add to Home Screen. It opens full screen and the cards you have read stay available offline.
We are hiring for this. Open roles that interview on nodejs — each one lists the topics its interview covers.
See open roles