Skip to main content
Version: v10.5.0

Client

Read the API Reference »

The Client is the central configuration object for one backend. It owns the base URL, the adapter, the cache, the two dispatchers and the managers, and it creates every request. Each client is isolated, so two clients never share cache, queues or interceptors.

Purpose
  1. Builds requests with createRequest, which inherit its configuration.
  2. Holds global behavior: auth, interceptors, request defaults and plugins.
  3. Owns the modules: adapter, cache, dispatchers and managers.
api/client.ts
import { createClient } from "@hyper-fetch/core";

type ApiError = { message: string; code: number };

// Keep Error in the union: timeouts, aborts and network failures arrive as
// Error instances
export const client = createClient<{ error: ApiError | Error }>({
url: "https://api.example.com",
});

export const getUser = client.createRequest<{
response: { id: number; name: string };
}>()({
endpoint: "/users/:userId",
});

Create the client once and export it. The error generic is the global error type, merged with each request's own error type. See global error for the patterns.


Add authentication​

onAuth runs before every request with auth: true, which is the default. Return the request with the headers it needs. Mark public endpoints auth: false to skip it.

api/client.ts
client.onAuth((request) => {
const token = localStorage.getItem("token");
return token
? request.setHeaders({
...request.headers,
Authorization: `Bearer ${token}`,
})
: request;
});

const getHealth = client.createRequest()({ endpoint: "/health", auth: false });

The authentication guide covers token refresh on 401.


Intercept requests and responses​

Interceptors run in this order: onRequest, onAuth (only when auth is on), the adapter, then onResponse, and onSuccess or onError. Request interceptors return a request, response interceptors return a response.

MethodRuns onRemove with
onRequestEvery request before it is sentremoveOnRequestInterceptors
onAuthRequests with auth: trueremoveOnAuthInterceptors
onResponseEvery responseremoveOnResponseInterceptors
onSuccessSuccessful responsesremoveOnSuccessInterceptors
onErrorFailed responsesremoveOnErrorInterceptors
api/client.ts
client.onError(async (response, request) => {
// `used` stops a resent request from refreshing again
if (response.status !== 401 || request.used) return response;
await refreshToken();
return request.setUsed(true).send();
});

A request can skip them with disableRequestInterceptors or disableResponseInterceptors. The interceptors guide has more patterns.


Set defaults for every request​

Request defaults live on the adapter. setRequestDefaults takes a callback with the options of each new request and returns the defaults to apply. Options set on a request always win.

api/client.ts
client.adapter
.setRequestDefaults((options) => {
const method = options.method ?? "GET";
// The callback replaces the built-in default, so keep deduplication for reads
if (method === "GET" || method === "QUERY")
return { deduplicate: true, retry: 2 };
return { retry: 0 };
})
// fetch options, the timeout is 5000 ms by default
.setAdapterDefaults(() => ({ timeout: 10_000 }));

Call both before you create requests: defaults are read when a request is created. See global defaults.


Change the base URL​

setUrl points the client at another server, for example when switching tenants or regions. Cache keys do not include the base URL, so data of the old server stays until you invalidate it.

api/client.ts
client.setUrl("https://us.example.com", { abort: true, invalidate: true });
OptionDefaultDescription
abortfalseAbort requests still in progress for the old URL.
invalidatefalseInvalidate the whole cache, so mounted hooks refetch from the new URL.

Cache safely on the server​

The mode option decides how the cache behaves. Default "auto": "client" in the browser, React Native and Electron, which serve one user, and "server" in Node.js, Deno, Bun and edge runtimes. Change it with mode: "client" or mode: "server".

In "server" mode nothing is cached unless the request has a scope, so one user's data never reaches another. Read client.mode for the resolved value.

server.ts
// Cached for this session only
const { data } = await getUser
.setParams({ userId: 1 })
.setScope(session.id)
.send();

See Cache for scopes.


Hydrate data from the server​

request.dehydrate() packs a response for the browser, and client.hydrate() writes it into the cache there.

Server and browser
// On the server
const response = await getUser.setParams({ userId: 1 }).send();
const state = [getUser.setParams({ userId: 1 }).dehydrate({ response })];

// In the browser, before the components read the cache
client.hydrate(state);

In React, render the Hydrate component instead. It writes the data before the hooks mount and never replaces newer cache data with an older snapshot.


Add plugins​

Plugins observe the request, cache and dispatcher lifecycle. addPlugin mounts one, removePlugin unmounts it.

api/client.ts
import { DevtoolsPlugin } from "@hyper-fetch/plugin-devtools";

client.addPlugin(DevtoolsPlugin({ appName: "My App" }));

See Plugin to write your own.


Reset the client​

clear() aborts every request, empties both dispatchers and the cache (including lazyStorage), and creates the modules again from the client options. Call it on logout and between tests.

auth/logout.ts
client.clear();

Options​

OptionDefaultDescription
urlrequiredBase URL of every request.
mode"auto"Cache mode: "auto", "client" or "server".
cache() => new Cache()Factory of the cache, for example with lazyStorage.
appManager() => new AppManager()Factory of the focus and online state manager.
fetchDispatcher() => new Dispatcher()Factory of the dispatcher for GET and QUERY requests.
submitDispatcher() => new Dispatcher()Factory of the dispatcher for every other method.

The other settings have setters: setAdapter, setDebug, setLogLevel, setEnableGlobalMocking, and setCacheKeyMapper, setQueryKeyMapper, setAbortKeyMapper to change how keys are built.


Methods​

Methods
Name Description
triggerPlugins(key, data)
setUrl(url, options)
Set the base url used by the next requests - e.g. when switching tenants, regions or environments at runtime. Cache keys don't include the base url, so data cached for the previous url stays in place unless you passinvalidate: true . Pass abort: true to cancel the requests that are still in progress for the previous url.
setRequestIdMapper(callback)
Set a custom mapper that generates the unique request ID for deduplication and tracking.
setQueryKeyMapper(callback)
Set a custom mapper that generates the query key used to identify requests in the dispatcher queue.
setLogger(callback)
Set the new logger instance to the Client
setLogLevel(severity)
Set the logger severity of the messages displayed to the console
setEnableGlobalMocking(isMockerEnabled)
Set globally if mocking should be enabled or disabled for all client requests.
setDebug(enabled)
This method enables the logger usage and display the logs in console
setCacheKeyMapper(callback)
Set a custom mapper that generates the cache key used to store and retrieve cached responses.
setAdapter(adapter)
Set custom http adapter to handle graphql, rest, firebase or others
setAbortKeyMapper(callback)
Set a custom mapper that generates the abort key used to cancel in-flight requests.
removePlugin(plugin)
Remove plugins from Client
removeOnSuccessInterceptors(callbacks)
Method for removing listeners on success.
removeOnResponseInterceptors(callbacks)
Method for removing response interceptors.
removeOnRequestInterceptors(callbacks)
Method for removing listeners on request.
removeOnErrorInterceptors(callbacks)
Method for removing listeners on error.
removeOnAuthInterceptors(callbacks)
Method for removing listeners on auth.
onSuccess(callback)
Method for intercepting success responses.
onResponse(callback)
Method for intercepting any responses.
onRequest(callback)
Method of manipulating requests before sending the request.
onError(callback)
Method for intercepting error responses. It can be used for example to refresh tokens.
onAuth(callback)
Method of manipulating requests before sending the request. We can for example add custom header with token to the request which request had the auth set to true.
hydrate(hydrationData, options)
Hydrate your SSR cache data
fromJSON(json)
Reconstruct a Request class instance from its serialized JSON form. Useful when dispatcher storage serializes queue data (e.g. MMKV, AsyncStorage) and the deserialized request loses its class identity.
createRequest(_USE_DOUBLE_INITIALIZATION)
Create requests based on the Client setup
clear()
Clears the Client instance and remove all listeners on it's dependencies
addPlugin(plugin)
Add persistent plugins which trigger on the request lifecycle


Summary
  • Create one client per backend with createClient and type its global error.
  • Put auth, interceptors and defaults on the client, so every request gets them.
  • Use setScope on the server, hydrate to pass data to the browser and clear() on logout.

Next steps​

Runnable examples: Authentication, Retry-After (a client interceptor) and Plugins.

Client setup
Ways to create and configure the client.
Request
Define endpoints and send them.
Client API reference
Every method of the Client class with its signature.