@hyper-fetch/sockets
v10.5.1
Published
Typed WebSocket and Server-Sent Events client for HyperFetch, with reconnects, backoff, heartbeat and offline handling
Readme
📖 About
@hyper-fetch/sockets is the realtime side of Hyper Fetch. It puts WebSockets and Server-Sent Events behind one API of
typed listeners and emitters, with reconnects, authentication per connection attempt and delivery strategies for fast
streams. Listeners and emitters are immutable templates, just like core requests, and plug into React through
useListener and useEmitter.
🎯 Key Capabilities
- 🔮 Typed events - Every listener and emitter is typed, so
datais never aJSON.parseguess - 🧭 Typed topic params -
chat/:roomIdmakesroomIdrequired onsetParams()andemit() - 📡 WebSocket and SSE, one API - Switch the adapter and keep your listeners
- 🔁 Reconnects on its own - Jittered backoff, an immediate retry when the app is back online or in focus
- 🎧 Listeners survive outages - Every listener stays registered across reconnects
- 🔐 Fresh tokens on every attempt -
onConnectresolves credentials before each connection and reconnection - 🚦 Tame fast streams -
latestandbatchdelivery strategies throttle or batch messages per listener - 🧱 Your wire format -
decodeandencodemap any message shape to topics, no custom adapter needed - ⚛️ React hooks -
useListeneranduseEmitterfrom@hyper-fetch/reacthandle subscribe and cleanup
🚀 Quick Start
npm install @hyper-fetch/core @hyper-fetch/socketsimport { createSocketClient } from "@hyper-fetch/sockets";
// One socket per server connection, created once at module level
const socket = createSocketClient({ url: "wss://api.example.com/ws" });
const onMessage = socket.createListener<{ text: string; author: string }>()({
topic: "chat/:roomId",
});
// roomId is required and typed. listen() returns the remover
const stop = onMessage.setParams({ roomId: "general" }).listen(({ data }) => {
console.log(`${data.author}: ${data.text}`);
});📚 Documentation
- Quick Start - Connect and listen in a few lines
- Socket - Connection options, reconnects and lifecycle events
- Listener and Emitter - Typed messages in both directions
- Socket SDK - A typed tree of listeners and emitters from a schema
- Authentication - Tokens per attempt with
onConnect - Throttling -
latestandbatchdelivery - API Reference - Every class, option and type
💡 Examples
Emit typed events
const sendMessage = socket.createEmitter<{ text: string }>()({ topic: "chat/:roomId" });
sendMessage.emit({ params: { roomId: "general" }, payload: { text: "Hello" } });emit() is fire and forget. A message emitted while the socket is disconnected is dropped and reported through
socket.events.onEmitterError, so gate the UI on connected.
Authenticate every connection attempt
export const socket = createSocketClient({ url: "wss://api.example.com/ws" }).onConnect(async ({ connection, attempt }) => {
// attempt is 0 for a fresh connection, so refresh the token only on reconnects
const token = await getAccessToken({ forceRefresh: attempt > 0 });
return { ...connection, queryParams: { token } };
});Throttle a fast stream
// State-like data: only the newest price per 16ms frame
const onPrice = socket.createListener<{ symbol: string; value: number }>()({
topic: "prices",
delivery: { strategy: "latest", interval: 16 },
});
// Event-like data: every trade, delivered as arrays per 100ms window
const onTrade = socket.createListener<{ id: string; price: number }>()({
topic: "trades",
delivery: { strategy: "batch", interval: 100, maxSize: 500 },
});
onTrade.listen(({ data }) => appendTrades(data)); // data is an array of tradesLive chat in React
import { useEmitter, useListener } from "@hyper-fetch/react";
const Chat = ({ roomId }: { roomId: string }) => {
const { data, connected } = useListener(onMessage.setParams({ roomId }));
const { emit } = useEmitter(sendMessage);
return (
<>
<StatusDot online={connected} />
{data && <Message author={data.author} text={data.text} />}
<Composer onSend={(text) => emit({ params: { roomId }, payload: { text } })} />
</>
);
};Server-Sent Events
import { createSocketClient, ServerSentEventsAdapter } from "@hyper-fetch/sockets";
const events = createSocketClient({ url: "https://api.example.com/events", adapter: ServerSentEventsAdapter() });
const onDeploy = events.createListener<{ service: string; status: "started" | "done" }>()({ topic: "deploy" });
onDeploy.listen(({ data }) => console.log(`${data.service} ${data.status}`));SSE is receive-only, so emit() on an SSE socket throws.
Keep the HTTP cache in sync
const onNoteChange = socket.createListener<Note>()({ topic: "notes" });
onNoteChange.listen(({ data }) => {
// every useFetch(getNote) for this note re-renders with the pushed data
client.cache.update(getNote.setParams({ noteId: data.id }), { data });
});🧩 Hyper Fetch Ecosystem
One typed client for every backend. Swap the adapter and keep the same createRequest() everywhere.
