react-ws-manager
v0.1.1
Published
Type-safe WebSocket manager for real-time applications. Framework-agnostic core with first-class React support. Supports multi-endpoint connections, auto-reconnect, and subscription-based messaging.
Downloads
13
Maintainers
Readme
react-ws-manager
|
🇺🇸 English | 🇰🇷 Korean
⚡ A framework-agnostic WebSocket manager for real-time apps with first-class React support.
🧠 Why not just use native WebSocket?
Because this is what happens in real apps:
- ❌ multiple connections → duplicated logic
- ❌ reconnect handling → inconsistent
- ❌ state sync → manual
- ❌ scaling → painful
This library solves all of that.
🏭 Built for real-world systems
This library was originally built for:
- multi-service architectures (MSA)
- event-driven backend systems
- real-time monitoring dashboards
Where:
- each service exposes its own WebSocket endpoint
- UI needs to subscribe to multiple streams
- state must stay consistent across features
✨ Why this exists
❗ Problem
Most WebSocket implementations in React apps look like this:
- scattered
useEffecthooks - duplicated reconnect logic
- hard-to-track connection state
- messy event handling
- impossible to scale across multiple endpoints
💡 Solution
This library provides a centralized, type-safe WebSocket layer:
- manage multiple WebSocket connections
- subscribe to messages declaratively
- auto reconnect with exponential backoff
- built-in heartbeat support
- queue messages before connection opens
- fully typed message handling
- React integration out of the box
🎯 When should you use this?
This library is designed for applications that:
- use multiple WebSocket endpoints
- consume real-time events from different services
- need structured subscription-based messaging
- want to avoid scattered WebSocket logic
Real-world examples
- 🏭 Manufacturing / IoT monitoring systems
- 📊 Real-time dashboards (logs, metrics, alerts)
- 💬 Multi-channel chat applications
- 🚨 Event-driven notification systems
⚡ Features
- 🔌 Multi-endpoint WebSocket management
- 🔁 Auto reconnect (exponential backoff + retry control)
- ❤️ Heartbeat support for connection stability
- 📬 Message queue before connection is ready
- 📡 Subscription-based event system
- 🧠 Fully type-safe (TypeScript-first)
- ⚛️ React hooks (useWebSocket)
- 🌲 Tree-shakable design (core + react split)
- 🚀 SSR-safe (Next.js compatible)
🔥 Without vs With
❌ Without this library
useEffect(() => {
const ws = new WebSocket(url);
ws.onmessage = (e) => { ... };
ws.onclose = () => reconnect();
return () => ws.close();
}, []);- manual reconnect logic
- duplicated code
- hard to scale
- no structure
✅ With react-ws-manager
const { data, status } = useWebSocket('event');- declarative subscriptions
- centralized connection management
- built-in reconnect & heartbeat
- type-safe message flow
📦 Installation
npm install react-ws-manager🚀 Quick Start (with React)
import { createWebSocketManager } from 'react-ws-manager';
import { WebSocketProvider, useWebSocket } from 'react-ws-manager/react';
type WS = {
chat: { text: string };
};
const ws = createWebSocketManager<WS>({
baseUrl: 'ws://localhost:8080',
endpoints: { chat: '' },
});
function App() {
return (
<WebSocketProvider manager={ws}>
<Chat />
</WebSocketProvider>
);
}
function Chat() {
const { data, status } = useWebSocket<WS, 'chat'>('chat');
return (
<div>
<p>Status: {status}</p>
<pre>{JSON.stringify(data)}</pre>
</div>
);
}👉 No useEffect. No manual reconnect logic.
🧠 TypeScript Support
type WS = {
event: { id: number; message: string };
chat: { user: string; text: string };
};
const ws = createWebSocketManager<WS>({
baseUrl: 'ws://localhost:8080',
endpoints: {
event: '/event',
chat: '/chat',
},
});👉 Fully typed messaging out of the box.
⚙️ Advanced Configuration
const ws = createWebSocketManager({
baseUrl: 'ws://localhost:8080',
endpoints: { event: '/event' },
parser: (e) => JSON.parse(e.data),
serializer: (data) => JSON.stringify(data),
retry: {
attempts: 5,
delay: (count) =>
Math.min(1000 * 2 ** count, 30000),
},
heartbeat: {
interval: 10000,
message: () => 'ping',
},
debug: true,
autoConnect: true
});📁 Import API
// Core
import { createWebSocketManager } from 'react-ws-manager';
// React
import { useWebSocket, WebSocketProvider } from 'react-ws-manager/react';🧩 API
createWebSocketManager(options)
| Option | Description |
| ------------ | ---------------------- |
| baseUrl | WebSocket base URL |
| endpoints | Endpoint map |
| parser | Custom message parser |
| serializer | Custom send serializer |
| retry | Reconnect strategy |
| heartbeat | Heartbeat config |
| debug | Enable logs |
| autoConnect| Enable Autoconnect |
Methods
ws.connect(key)
ws.close(key)
ws.subscribe(key, handler)
ws.subscribeStatus(key, handler)
ws.send(key, message)
ws.getStatus(key)🏗 Architecture
React App
↓
useWebSocket
↓
WebSocketProvider
↓
WebSocket Manager
↓
Multiple WebSocket Connections
↓
Backend Services💡 Design Philosophy
- WebSocket should feel like state, not side-effects
- Core is framework-agnostic
- React is just a thin adapter
- Subscription over polling
- Built for real-world systems (not toy examples)
📌 Notes
- React is a peer dependency (>=18)
- Works with Next.js, Vite, CRA
- SSR-safe
- No unnecessary re-renders
📄 License
⭐ Support
If this project helps you, please consider giving it a star ⭐
It really helps the project grow.
