A WebSocket that puts itself back together

Connections drop β€” on trains, in lifts, when a load balancer recycles. universal-realtime handles the recovery so your app doesn't have to. Four things it does, each one you can try below.

npm i universal-realtime 8 KB Β· zero dependencies Β· MIT

1. Connect

One class. It starts connecting the moment you construct it, and tells you the state as it changes.

// works in React, Vue, Node β€” no framework needed
import { RealtimeClient } from
  'universal-realtime/client';

const client = new RealtimeClient(
  'wss://api.example.com'
);

client.subscribeStatus(s => setStatus(s));
Live
open

The status is one of connecting, open, reconnecting or closed. Render it however you like.

2. It reconnects on its own

Kill the connection and it comes back β€” waiting longer after each failure so a recovering server isn't stampeded by every client at once.

new RealtimeClient(url, {
  reconnect: true,
  reconnectAttempts: 10,
});

// waits 1s, 2s, 4s, 8s … capped at 30s
// each wait is randomised Β±25% so a
// thousand clients don't return together
Try it
open
attemptβ€”
waitingβ€”

3. Messages sent while offline aren't lost

Send during an outage and the message waits in order, then goes out the moment the socket is back. You don't write any of that logic.

// socket is down right now β€”
// this does not throw, and is not lost
client.sendMessage({
  type: 'chat',
  body: 'sent while offline'
});

// …reconnects, then flushes in order
Try it

Connection is up β€” messages go straight out. Kill it in step 2 first, then send.

4. Presence, without a backend

Join a room and everyone in it sees you arrive. Lose your connection and you're removed automatically β€” no ghost users left behind.

const { users, count } = usePresence({
  wsUrl: 'wss://api.example.com',
  roomId: 'lobby',
  identity: { id: 'you' }
});

// leaving is automatic on disconnect
Try it