Connection
This guide provides a comprehensive overview of how to manage socket connections using Hyper-fetch. You'll learn how to control connection states, handle automatic and manual connections, and configure retry policies to build robust real-time applications.
- How to enable or disable automatic connections.
- How to manually connect and disconnect from the socket.
- How to implement manual reconnection logic.
- How to prepare every connection attempt with the
onConnectinterceptor. - How to monitor the connection status using callbacks.
- How to configure connection retries and handle reconnection failures.
Autoconnect
By default, Hyper-fetch attempts to connect to the socket server as soon as the Socket instance is created. This
behavior is controlled by the autoConnect option, which is set to true by default.
You can disable autoconnect by setting autoConnect: false in the adapter options. This is useful when you want to
delay the connection until a user performs a specific action, such as logging in or navigating to a certain page.
import { Socket } from "@hyper-fetch/sockets";
const socket = new Socket({
url: "ws://localhost:8080",
adapterOptions: { autoConnect: false },
});
When autoConnect is disabled, you'll need to manually initiate the connection.
Manual Connect
When autoConnect is disabled, you can manually establish a connection using the socket.connect() method. This gives
you precise control over when the connection is initiated.
function Component() {
const [socket] = React.useState(() => {
return new Socket({
url: "ws://localhost:8080",
adapterOptions: { autoConnect: false },
});
});
return (
<div>
<button onClick={() => socket.connect()}>Connect</button>
</div>
);
}
The connect method is asynchronous and returns a promise that resolves once the connection is established. Calling it
on an already connected socket keeps the current connection - use reconnect() to establish a fresh one.
Disconnect
You can manually close a socket connection using the socket.disconnect() method. This is useful for logging out a
user, leaving a specific feature area, or performing cleanup.
function Component() {
const [socket] = React.useState(() => {
return new Socket({
url: "ws://localhost:8080",
});
});
return (
<div>
<button onClick={() => socket.disconnect()}>Disconnect</button>
</div>
);
}
Like connect, the disconnect method is asynchronous and returns a promise that resolves once the connection is fully
closed.
Reconnect
Hyper-fetch provides a socket.reconnect() method to manually trigger a reconnection attempt. This can be useful in
scenarios where you want to give users a way to re-establish a connection without a full page reload, such as when a
connection is lost due to a temporary network issue.
function Component() {
const [socket] = React.useState(() => {
return new Socket({
url: "ws://localhost:8080",
});
});
return (
<div>
<button onClick={() => socket.reconnect()}>Reconnect</button>
</div>
);
}
reconnect() replaces the connection with a new one right away. A reconnection by hand is a fresh start: it is never
refused by the reconnect attempt limit, also after the automatic attempts ran out.
Preparing the Connection
Every connection attempt - the initial one, automatic reconnects and manual reconnects - goes through the onConnect
interceptor. It receives the connection details (url, queryParams, adapterOptions) and the reconnection attempt
number, and must return the details to use. It can be async, which makes it the right place to resolve anything that
changes over time: auth tokens, the selected workspace, feature flags.
import { Socket } from "@hyper-fetch/sockets";
const socket = new Socket({
url: "ws://localhost:8080",
}).onConnect(async ({ connection, attempt }) => {
const token = await auth.getValidAccessToken({ forceRefresh: attempt > 0 });
return { ...connection, queryParams: { token } };
});
Register the interceptor right after creating the socket - callbacks chained on the constructor apply to the automatic
first connection as well. If the interceptor throws, the attempt fails and the error is passed to the onError
callbacks.
Connection Status
To monitor the socket's connection status, you can use the onConnected and onDisconnected callbacks. These allow you
to react to changes in the connection state and update your UI accordingly.
onConnected: Triggered when the socket successfully connects.onDisconnected: Triggered when the socket connection is closed, either manually or due to a network issue.
Here's how you can use these callbacks to track the connection status:
function Component() {
const [isConnected, setConnected] = React.useState(false);
const [socket] = React.useState(() => {
const instance = new Socket({
url: "ws://localhost:8080",
});
instance.onConnected(() => {
setConnected(true);
console.log("Socket connected");
});
instance.onDisconnected(() => {
setConnected(false);
console.log("Socket disconnected");
});
return instance;
});
return (
<div>
<p>Status: {isConnected ? "Connected" : "Disconnected"}</p>
</div>
);
}
For React applications, consider using the useSocketState hook from @hyper-fetch/react for a more declarative way to
handle connection states.
Retries
When a connection is lost, the socket gets it back on its own. Every adapter - WebSocket, SSE, tRPC, oRPC - shares the same reconnection rules:
- Backoff with jitter. The first retry comes after
reconnectTimeto twice that, and the window doubles with every attempt up tomaxReconnectTime. Each client picks a random moment in the window, so the clients of a restarted server don't all come back at once. - Stable connections reset the counter. The attempt counter resets only once a connection stays up for
minUptime. A connection that drops right after opening - for example a server that accepts and then closes over an expired token - keeps backing off and counts towardsreconnect. - Every loss is retried unless
shouldReconnectsays otherwise - except a normal closure (1000) of the server, which means it finished on purpose. That one stays closed untilconnect(),reconnect()or the network coming back. Closing the socket yourself is never retried. - One timeout to be connected.
connectionTimeoutlimits how long an attempt may take until the connection can carry messages, including protocol handshakes. A timed out attempt is a failed attempt and the next one follows the backoff.
| Option | Default | Description |
|---|---|---|
reconnect | Infinity | How many reconnection attempts run before the socket gives up |
reconnectTime | 1000 | Minimum delay in ms before an attempt |
maxReconnectTime | 30000 | Maximum delay in ms before an attempt |
minUptime | 5000 | How long in ms a connection stays up before the attempt counter resets |
connectionTimeout | 5000 | How long in ms one attempt may take until the connection is ready |
reconnectDelay | jitter | ({ attempt, elapsed, reason }) => number | null - replaces the backoff |
shouldReconnect | 1000 stays | ({ code, reason, error }) => boolean - decides which lost connections are retried |
Customizing Retry Logic
Change the limits with the options above, or take over the timing with reconnectDelay. It receives the attempt number
of the outage (from 0), the time since the outage began and why the connection was lost. Return the delay in
milliseconds, or null to stop reconnecting.
import { Socket, defaultShouldReconnect } from "@hyper-fetch/sockets";
const socket = new Socket({
url: "ws://localhost:8080",
// Retry quickly a few times, then every 10 seconds, and give up after 5 minutes
reconnectDelay: ({ attempt, elapsed }) => {
if (elapsed > 5 * 60_000) return null;
return attempt < 3 ? 500 : 10_000;
},
// A rejected token won't get better by retrying - and a normal closure (1000) stays closed, like by default
shouldReconnect: (loss) => defaultShouldReconnect(loss) && loss.code !== 4401,
});
Handling Reconnection Events
You can also hook into the reconnection lifecycle with onReconnect and onReconnectFailed callbacks:
onReconnect: Triggered at the start of each reconnection attempt.onReconnectFailed: Triggered when all reconnection attempts have failed.
function Component() {
const [socket] = React.useState(() => {
const instance = new Socket({
url: "ws://localhost:8080",
reconnect: 3,
reconnectTime: 2000,
});
instance.onReconnect(() => {
console.log("Reconnection attempt started");
});
instance.onReconnectFailed(() => {
console.error("All reconnection attempts failed.");
});
return instance;
});
return <div>Check the console for reconnection events.</div>;
}
Offline handling
Every socket tracks the network and the focus of the app with its own AppManager (socket.appManager). In the browser
it listens to the window online / offline events and to the page visibility:
- Going offline closes the connection right away - a connection on a network that is gone can hang for minutes before the transport notices. No attempts run while offline, and none are counted.
- Coming back online connects at once, without waiting for the backoff.
- Getting the focus back skips the rest of a pending reconnection delay, so a user returning to the tab doesn't wait. Attempts still run in the background.
This applies to every socket that should be connected - from the first connection, automatic with autoConnect or by
hand with connect(), until disconnect(). autoConnect only decides the first connection.
In environments without these browser events, like React Native or Node.js, pass your own app manager with the
appManager option. Return a cleanup function from onlineEvent so that socket.appManager.unmount() can remove the
listener.
import { AppManager } from "@hyper-fetch/core";
import { Socket } from "@hyper-fetch/sockets";
// import NetInfo from "@react-native-community/netinfo";
const socket = new Socket({
url: "ws://localhost:8080",
appManager: () =>
new AppManager({
initiallyOnline: async () => Boolean((await NetInfo.fetch()).isConnected),
onlineEvent: (setOnline) => NetInfo.addEventListener((state) => setOnline(Boolean(state.isConnected))),
}),
});
You now know how to manage socket connections in Hyper-fetch.
- You can control automatic and manual connections.
- You can disconnect and reconnect from the server on demand.
- You can prepare every connection attempt with the
onConnectinterceptor. - You can monitor the connection lifecycle with callbacks.
- You can create robust retry strategies for network resilience.
- You can react to the network state and plug in your own
AppManager.

