Skip to main content
Version: 5.x.x

Socket Class


Socket is a class that allows you to configure the server connection. It initializes the entire library’s subsystems, such as offline, events, and interceptors. It also allows to create (based on its settings) the listeners and emitters necessary to execute requests. This way the data and information flow remains locked inside a given socket - it is isolated and does not affect other sockets.


  • Orchestrates the components and flow of the sockets library
  • Creates listeners and emitters to provide global setup and environment
  • Isolates sockets from other sockets and their events


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

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



You can pick between two built-in modes for the data exchange.

  1. Websocket mode (default)
  2. Server Sent Events mode

You can change it with SSE adapter.

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

new Sockets({ url: "ws://localhost:3000" }).setAdapter(sseAdapter);


To exchange authenticated events, set up the auth parameter with authentication query params. Later on, you can change the auth value with setAuth method, which after setting up the new data will reconnect the socket server. Read more about authentication here.

Read More

On-Emitting Interceptors

Use the onSend socket method if you need to use the pre-emitting interceptor to modify the Emitter before it’s sent.

On-Message Interceptors

There are few methods for intercepting a response from a request:

  • onError which is triggered on error from socket.
  • onMessage which is triggered on any received message.

We can modify received data with this interceptor before it will be emitted to other sub-systems.

Query Params

Sockets has a built-in query params encoding function; you can modify its options or provide your own function. Use the queryParamsConfig method and the options listed below.

arrayFormat: bracket | index | comma | separator | bracket-separator | none;
arraySeparator: string;
dateParser: (value: QueryParamType) => string;
encode: boolean;
objectParser: (value: QueryParamType) => string;
skipEmptyString: boolean;
skipNull: boolean;
strict: boolean;

To change the encoding function, use the queryParamsStringify method.

export const socket = new Sockets({
url: "ws://localhost:3000",
queryParams: { param1: [1, 2, 3], param2: "test" },
queryParamsStringify: (value: string) => encode(value),


Sockets has one generic type responsible for the type of the current Socket Adapter. It defaults to the built-in adapter type.

class Sockets<SocketAdapterType>

It needs to fulfill the SocketAdapterType interface.

(socket: Socket<SocketAdapterType<AdapterOptions, AdapterExtra, ListenerOptions, EmitterOptions>>, DO_NOT_USE?: [object Object]) => [object Object]