@hyper-fetch/sockets
v8.2.0
Published
Sockets connection for hyper-fetch
Readme
🛰️ Hyper Fetch Sockets
📖 About
@hyper-fetch/sockets provides a typed abstraction for real-time communication. It wraps WebSockets and Server-Sent Events behind a consistent API with typed listeners and emitters, automatic reconnection, offline queuing, and authentication support.
🎯 Key Capabilities
- 🔮 Type-safe events — Every listener and emitter is typed end-to-end, no more
JSON.parseguessing - 📡 WebSocket + SSE, one API — Switch between protocols without rewriting your event handlers
- 🔁 Never lose connection — Auto-reconnect with exponential backoff handles flaky networks for you
- 📴 Offline event queuing — Events you emit offline are saved and sent when connection returns
- 🔐 Auth built in — Token and session-based authentication flows for socket connections
- ⚛️ React hooks included —
useListeneranduseEmitterplug real-time data straight into components - 🖥️ SSR safe — Import in server-rendered apps without breaking hydration
🚀 Quick Start
npm install @hyper-fetch/socketsimport { Socket } from "@hyper-fetch/sockets";
const socket = new Socket({ url: "ws://localhost:3000" });
const onMessage = socket.createListener<{ response: { text: string; author: string } }>()({
endpoint: "chat-message",
});
onMessage.listen({ callback: ({ data }) => console.log(`${data.author}: ${data.text}`) });📚 Documentation
💡 Examples
Emitting typed events
const sendMessage = socket.createEmitter<{ payload: { text: string; room: string } }>()({
endpoint: "send-message",
});
sendMessage.emit({ data: { text: "Hello!", room: "general" } });Listening with React hooks
import { useListener } from "@hyper-fetch/react";
const ChatMessages = ({ room }: { room: string }) => {
const { data, connected, timestamp } = useListener(onMessage);
return (
<div>
<p>Status: {connected ? "Connected" : "Disconnected"}</p>
{data && (
<div>
<strong>{data.author}</strong>: {data.text}
<small>{new Date(timestamp).toLocaleTimeString()}</small>
</div>
)}
</div>
);
};Server-Sent Events
const sseSocket = new Socket({ url: "https://api.example.com/events" });
const onUpdate = sseSocket.createListener<{ response: { type: string; payload: unknown } }>()({
endpoint: "data-update",
});
onUpdate.listen({
callback: ({ data }) => console.log(`Event: ${data.type}`, data.payload),
});