npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

universal-realtime

v1.4.1

Published

Premium, lightweight, isomorphic full-stack real-time engine and hooks framework for React, Node.js, and browser environments. Features resilient WebSocket auto-reconnections, exponential backoff with jitter, offline event buffers, active pings, presence

Readme

universal-realtime

A premium, lightweight, zero-dependency real-time engine and hooks package for JavaScript, TypeScript, Node.js, and React.

universal-realtime delivers a high-performance framework-agnostic client (RealtimeClient) alongside ultra-optimized React wrappers. It provides out-of-the-box support for auto-reconnection (exponential backoff), customizable heartbeats (ping/pong), Server-Sent Events, user presence, and optimistic UI updates.


Try it without installing anything: Reconnect Console →
Cut the connection and watch the backoff, the offline queue and presence rooms react.

Key Features

  • Framework-Agnostic Core: Build with RealtimeClient in vanilla JS/TS, Node.js (via custom WebSocket constructors), Angular, Vue, Svelte, or SSR environments (Next.js/Remix safe). Import it from universal-realtime/client, which pulls in no React at all — React is only needed for the hooks on the root entry.
  • Multiplexed React Hooks: Streamline app performance using RealtimeProvider and useRealtime to share a single, robust connection across many components with zero React Context render cascades.
  • Traffic-Aware Heartbeats: Minimize unnecessary bandwidth with keep-alive heartbeats that only ping when the websocket connection is idle.
  • Auto-Reconnection: Resilient reconnection using a custom exponential backoff manager.
  • Zero Dependencies & Tree-Shakable: Built using modern ES tooling compiling to a microscopic size (~8 KB minified).

Installation

npm install universal-realtime

Framework-Agnostic Engine (RealtimeClient)

Perfect for pure JS/TS scripts, backend Node.js, or any non-React frameworks.

Import from the /client subpath. It contains only the core engine and never imports React, so it works in projects that don't have React installed:

import { RealtimeClient } from 'universal-realtime/client';

// Instantiates client (gracefully safe in SSR)
const client = new RealtimeClient('ws://api.example.com', {
  reconnect: true,
  reconnectAttempts: 5,
  heartbeat: {
    interval: 30000,
    timeout: 5000,
    message: 'ping'
  }
});

// Subscribe to connection status changes
const unsubscribeStatus = client.subscribeStatus((status) => {
  console.log('Connection status is:', status); // 'connecting' | 'open' | 'closing' | 'closed' | 'reconnecting'
});

// Subscribe to incoming messages
const unsubscribeMessages = client.subscribe((message) => {
  console.log('Received:', message);
});

// Send a message
client.sendMessage({ type: 'greet', body: 'hello' });

// Cleanup
unsubscribeStatus();
unsubscribeMessages();
client.disconnect();

Node.js Support

In backend Node.js environments (where native WebSocket might not be globally available), pass a custom WebSocket constructor (e.g. from the ws package):

import { RealtimeClient } from 'universal-realtime/client';
import WebSocket from 'ws'; // node WebSocket library

const client = new RealtimeClient('ws://api.example.com', {
  webSocketConstructor: WebSocket,
});

Advanced Core Features

1. Dynamic Authentication Handshake

You can supply an asynchronous auth parameter to dynamically resolve authentication credentials or tokens before opening a connection. The returned key-value pairs are automatically appended as connection query parameters:

const client = new RealtimeClient('ws://api.example.com', {
  auth: async () => {
    const token = await fetchSecureToken();
    return { token, clientVersion: '1.3.0' };
  }
});

2. Automatic Offline Event Queuing

If the client is offline or re-establishing a connection, any message sent via sendMessage() is automatically cached in an internal FIFO queue and flushed in order the moment a connection is established.

3. Reconnection Jitter

Avoid "thundering herd" server bottlenecks. Toggle randomized ±25% reconnection jitter to stagger client reconnection attempts:

const client = new RealtimeClient('ws://api.example.com', {
  reconnect: true,
  reconnectJitter: true, // staggered reconnection delays
});

4. Raw Connection Passthrough (unwrap)

Access the raw, typed underlying WebSocket instance safe and casted:

const rawSocket = client.unwrap<WebSocket>();

React Hooks API (Thin Wrappers)

1. Central Connection Provider (RealtimeProvider + useRealtime)

Multiplexes all real-time events over exactly 1 WebSocket connection to reduce client resource load and prevent global React Context render cascades.

import React from 'react';
import { RealtimeProvider, useRealtime } from 'universal-realtime';

function App() {
  return (
    <RealtimeProvider url="ws://api.example.com">
      <MessageList />
    </RealtimeProvider>
  );
}

function MessageList() {
  // Selective rendering: only re-renders when filters match!
  const { lastMessage, sendMessage, connectionStatus } = useRealtime<string>(
    (msg) => msg.startsWith('important:')
  );

  return (
    <div>
      <p>Connection: {connectionStatus}</p>
      <p>Last Important Message: {lastMessage}</p>
      <button onClick={() => sendMessage('Hello!')}>Send</button>
    </div>
  );
}

2. Standalone Hook (useWebSocket)

For simple, component-isolated WebSocket connections.

import { useWebSocket } from 'universal-realtime';

function MyComponent() {
  const { lastMessage, sendMessage, connectionStatus } = useWebSocket('ws://api.example.com');
  
  return <div>Status: {connectionStatus}</div>;
}

3. Server-Sent Events (useSSE)

Robust stream consumer with built-in auto-reconnection.

import { useSSE } from 'universal-realtime';

function EventStream() {
  const { data, connectionStatus } = useSSE('https://api.example.com/stream');
  
  return <div>Data: {data} | Connection: {connectionStatus}</div>;
}

4. Room Presence (usePresence)

Track "who's online" in real-time rooms.

import { usePresence } from 'universal-realtime';

function ChatRoom() {
  const { users, count } = usePresence({
    wsUrl: 'ws://api.example.com/presence',
    roomId: 'lobby',
    identity: { id: 'user-1', metadata: { name: 'Junaid' } }
  });

  return <div>Active Users ({count}): {users.map(u => u.metadata.name).join(', ')}</div>;
}

5. Optimistic UI Updates (useOptimisticUpdate)

Instantly update the user interface and seamlessly roll back state if the network mutation fails.

import { useOptimisticUpdate } from 'universal-realtime';

function TodoList({ initialTodos }) {
  const { data: todos, update, isPending } = useOptimisticUpdate(initialTodos);

  const addTodo = (newTodo) => {
    update([...todos, newTodo], async () => {
      // Async server call
      return await api.saveTodo(newTodo);
    });
  };

  return <button onClick={() => addTodo({ text: 'Buy milk' })}>Add Todo</button>;
}

License

MIT