Client
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.
- Builds requests with
createRequest, which inherit its configuration. - Holds global behavior: auth, interceptors, request defaults and plugins.
- Owns the modules: adapter, cache, dispatchers and managers.
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.
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.
| Method | Runs on | Remove with |
|---|---|---|
onRequest | Every request before it is sent | removeOnRequestInterceptors |
onAuth | Requests with auth: true | removeOnAuthInterceptors |
onResponse | Every response | removeOnResponseInterceptors |
onSuccess | Successful responses | removeOnSuccessInterceptors |
onError | Failed responses | removeOnErrorInterceptors |
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.
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.
client.setUrl("https://us.example.com", { abort: true, invalidate: true });
| Option | Default | Description |
|---|---|---|
abort | false | Abort requests still in progress for the old URL. |
invalidate | false | Invalidate 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.
// 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.
// 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.
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.
client.clear();
Options
| Option | Default | Description |
|---|---|---|
url | required | Base 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
| Name | Description |
|---|---|
| |
| 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. |
| Set a custom mapper that generates the unique request ID for deduplication and tracking. |
| Set a custom mapper that generates the query key used to identify requests in the dispatcher queue. |
| Set the new logger instance to the Client |
| Set the logger severity of the messages displayed to the console |
| Set globally if mocking should be enabled or disabled for all client requests. |
| This method enables the logger usage and display the logs in console |
| Set a custom mapper that generates the cache key used to store and retrieve cached responses. |
| Set custom http adapter to handle graphql, rest, firebase or others |
| Set a custom mapper that generates the abort key used to cancel in-flight requests. |
| Remove plugins from Client |
| Method for removing listeners on success. |
| Method for removing response interceptors. |
| Method for removing listeners on request. |
| Method for removing listeners on error. |
| Method for removing listeners on auth. |
| Method for intercepting success responses. |
| Method for intercepting any responses. |
| Method of manipulating requests before sending the request. |
| Method for intercepting error responses. It can be used for example to refresh tokens. |
| 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 your SSR cache data |
| 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. |
| Create requests based on the Client setup |
| Clears the Client instance and remove all listeners on it's dependencies |
| Add persistent plugins which trigger on the request lifecycle |
- Create one client per backend with
createClientand type its globalerror. - Put auth, interceptors and defaults on the client, so every request gets them.
- Use
setScopeon the server,hydrateto pass data to the browser andclear()on logout.
Next steps
Runnable examples: Authentication, Retry-After (a client interceptor) and Plugins.