Quick Start
Hyper Fetch's Sockets module enables real-time, bidirectional communication using WebSockets or other adapters. It's framework-agnostic and requires no external libraries to function.
- How to initialize the socket client
- How to create emitters and listeners
- How to interact with the server
-
Initialize the Socket Client
The first step is to initialize the Socket client. This manages the WebSocket connection and all real-time
communication. Specify the url of your WebSocket server.
import { createSocketClient } from "@hyper-fetch/sockets";
export const socket = createSocketClient({ url: "ws://localhost:3000" });
-
Create Emitters and Listeners
With your socket client set up, you can define emitters (to send events) and listeners (to receive events) for real-time communication.
Creating Listeners
Listeners subscribe to server events and provide type-safe callbacks.
import { socket } from "./socket";
export const onChatMessage = socket.createListener<ChatMessageType>()({
topic: "chat-message",
});
Creating Emitters
Emitters send typed events to the server.
import { socket } from "./socket";
export const sendChatMessage = socket.createEmitter<ChatMessageType>()({
topic: "chat-message",
});
Both listeners and emitters are fully typed, ensuring you always know the shape of your data.
-
Interact with the Server
Once you have your emitters and listeners, you can send and receive real-time events.
Listen to events
Just use the listen method and pass the callback function.
import { onChatMessage } from "./listeners";
onChatMessage.listen((data) => console.log(data));
Emit events
Just use the emit method and pass the data you want to send.
import { sendChatMessage } from "./emitters";
sendChatMessage.emit({ payload: { message: "Hello world" } });
Additional: Changing the adapter
By default, Sockets uses WebSocket adapter, but you can switch to SSE or provide your own adapter for maximum
flexibility. Pass the adapter via the adapter constructor option.
import { createSocketClient, ServerSentEventsAdapter } from "@hyper-fetch/sockets";
const socket = createSocketClient({
url: "http://localhost:3000",
adapter: ServerSentEventsAdapter(),
});
You've seen how straightforward it is to get started with Hyper Fetch Sockets for real-time communication.
