Skip to main content
Version: v7.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 { Socket } from "@hyper-fetch/sockets";

export const socket = new Socket({ 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>()({
endpoint: "chat-message", // event name or endpoint
});

Creating Emitters

Emitters send events to the server, optionally handling acknowledgements.

import { socket } from "./socket";

export const sendChatMessage = socket.createEmitter<ChatMessageType, AcknowledgementResponseType>()({
endpoint: "chat-message", // event name or endpoint
});
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";

onChatMessage.listen({ callback: (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({ data: { 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.

import { ServerSentEventsAdapter } from "@hyper-fetch/sockets";

socket.setAdapter(ServerSentEventsAdapter());

That's it!

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