---
sidebar_position: 3
title: Socket Class
sidebar_label: Socket
---

<div class="api-link">
  <div class="api-link-title">Socket</div>
  <div class="api-link-sub-title">

[Read the API Reference »](/api/Sockets/Class/Socket.mdx)

  </div>
</div>

---

## Introduction

**`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.

---

## Purpose

- 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

---

## Initialization

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

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

---

## Features

### Mode

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.

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

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

### Authentication

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](/guides/03-sockets/authentication.mdx)

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

{@import Hyper-Fetch QueryStringifyOptionsType returns}

To change the encoding function, use the `queryParamsStringify` method.

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

---

## Typescript

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

```tsx
class Sockets<SocketAdapterType>
```

It needs to fulfill the `SocketAdapterType` interface.

{@import Sockets SocketAdapterType returns}

---
