Skip to main content
Version: v8.0.0

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.

What you'll learn
  • How to initialize the socket client
  • How to create emitters and listeners
  • How to interact with the server

  1. 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.

socket.ts
import { createSocketClient } from "@hyper-fetch/sockets";

export const socket = createSocketClient({ url: "ws://localhost:3000" });

  1. 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",
});
tip

Both listeners and emitters are fully typed, ensuring you always know the shape of your data.


  1. 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";

// The callback receives an object with `data` and `extra` properties
onChatMessage.listen(({ data, extra }) => 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(),
});

That's it!

You've seen how straightforward it is to get started with Hyper Fetch Sockets for real-time communication.