WebSocket Server with ws
Create a WebSocket server with connection tracking, heartbeat ping/pong, and typed message handling.
import { WebSocketServer, WebSocket } from 'ws';
const wss = new WebSocketServer({ port: 8080 });
const clients = new Set<WebSocket>();
wss.on('connection', (ws) => {
clients.add(ws);
console.log(`Client connected (${clients.size} total)`);
ws.on('message', (raw) => {
const msg = JSON.parse(raw.toString());
// Broadcast to all other clients
for (const client of clients) {
if (client !== ws && client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify(msg));
}
}
});
ws.on('close', () => {
clients.delete(ws);
});
// Heartbeat
const interval = setInterval(() => {
if (ws.readyState === WebSocket.OPEN) ws.ping();
}, 30_000);
ws.on('close', () => clearInterval(interval));
});Use Cases
- Chat applications
- Live notifications
- Real-time dashboards
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
Graceful Server Shutdown
Handle SIGTERM and SIGINT signals to drain connections, close database pools, and exit cleanly.
JWT Verify Middleware
Express middleware that verifies JWT tokens from the Authorization header and attaches the decoded payload to the request.
In-Memory Rate Limiter for Express
Token bucket rate limiter middleware for Express with configurable window and max requests per IP.
Async Error Handler Wrapper
Higher-order function that wraps async Express route handlers and forwards rejected promises to error middleware.