A powerful WebSocket manager for handling multiple WebSocket connections dynamically with ease. Now includes WebSocket Server Support! π
Built on top of ws, this library enables event-driven WebSocket communication with minimal boilerplate code.
β
Create a WebSocket Server
β
Manage multiple WebSocket connections dynamically
β
Auto-reconnect when disconnected
β
Supports authentication (API keys, OAuth, JWT, headers) π
β
Dynamic message function execution (run functions from messages!)
β
Broadcast messages to all connected clients
β
Stores connected clients in memory for easy access
β
Works in both Frontend (Browser) & Backend (Node.js)
β
Lightweight & easy to integrate
npm install ws-multi-connect
With this, you no longer need ws separately!
const WebSocketManager = require("ws-multi-connect");
const wsManager = new WebSocketManager();
wsManager.startServer(5001); // Starts WebSocket server on port 5001
The library stores connected clients in wsManager.clients
, allowing easy retrieval and management.
console.log(
"π₯ Active WebSocket Clients:",
Array.from(wsManager.clients.keys())
);
wsManager.clients.forEach((client, url) => {
if (client.readyState === 1) {
client.send(JSON.stringify({ message: "Hello, everyone!" }));
}
});
wsManager.registerFunction("auth", (data, ws) => {
if (!data.token) {
console.error("β No token received!");
return;
}
console.log("π Verifying token...");
const decoded = jwt.verify(data.token, "YOUR_SECRET");
ws.userId = decoded.id; // β
Store user ID inside WebSocket object
wsManager.clients.set(ws.userId, ws); // β
Store user ID in `clients` Map
console.log("π₯ Active Users:", Array.from(wsManager.clients.keys()));
});
If you want your backend to connect as a WebSocket client:
const WebSocketManager = require("ws-multi-connect");
const wsManager = new WebSocketManager();
const wsUrl = "ws://localhost:5001";
wsManager.connect(wsUrl, {
onOpen: () => console.log("β
Backend Connected to WebSocket Server"),
onMessage: (msg) => console.log("π© Backend Received:", msg),
autoReconnect: true,
});
This allows the client (browser) to connect and send/receive messages.
import { WebSocketManager } from "ws-multi-connect";
const wsManager = new WebSocketManager();
const wsUrl = "ws://localhost:5001";
wsManager.connect(wsUrl, {
onOpen: () => console.log("π Frontend Connected"),
onMessage: (msg) => console.log("π© Received:", msg),
autoReconnect: true,
});
// Sending message from frontend
wsManager.send(wsUrl, { text: "Hello from frontend!" });
Here is an example of connecting to an external WebSocket API (e.g., cryptocurrency market data):
import { WebSocketManager } from "ws-multi-connect";
const wsManager = new WebSocketManager();
wsManager.connect("wss://example.com/v1/", {
// Replace with actual WebSocket URL
autoReconnect: true,
onOpen: (ws) => {
console.log("π Connected to External WebSocket API");
// β
Send API key inside the first message
const subscribeMessage = {
type: "hello",
apikey: "your-api-key", // β
Correct way to authenticate
heartbeat: false,
subscribe_data_type: ["trade"],
subscribe_filter_symbol_id: ["EXCHANGE_SPOT_BTC_USD"],
};
console.log(
"π€ Sending subscription message:",
JSON.stringify(subscribeMessage)
);
ws.send(JSON.stringify(subscribeMessage));
},
onMessage: (msg) => {
try {
console.log("π© Received trade data:", msg);
} catch (error) {
console.error("β οΈ Error parsing message:", msg);
}
},
onError: (error) => {
console.error("π¨ WebSocket error:", error);
},
onClose: () => {
console.log("β WebSocket connection closed");
},
});
Creates a WebSocket server.
Parameter | Type | Description |
---|---|---|
port |
number |
Port to start the WebSocket server |
const wsManager = new WebSocketManager();
wsManager.startServer(5001);
Connects to a WebSocket URL.
Parameter | Type | Description |
---|---|---|
url |
string |
The WebSocket server URL |
options |
object |
(Optional) Settings for the connection |
onOpen(ws)
: Callback when the WebSocket is opened.onMessage(message)
: Callback when a message is received.onError(error)
: Callback for WebSocket errors.autoReconnect
(default:false
): Whether to reconnect automatically.reconnectInterval
(default:5000ms
): Time before trying to reconnect.auth
: (Optional) Authentication details.
wsManager.connect("ws://localhost:5001", {
onOpen: () => console.log("β
Connected"),
onMessage: (msg) => console.log("π© Received:", msg),
});
Feel free to submit issues or PRs on GitHub.
MIT License Β© 2025 Haard Tripathi