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
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));
The status is one of connecting, open, reconnecting or closed. Render it however you like.
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
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
Connection is up β messages go straight out. Kill it in step 2 first, then send.
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