Client Setup
Every request in HyperFetch is created from a client, which holds the base URL, the adapter, the cache and the dispatchers for one backend. This guide creates a client, types its errors, shares it across the app and creates the first request from it.
- How to create a client with
createClientand a baseurl. - How to type the global error once for every request.
- How to share one client per backend and create requests from it.
- What the main client options change.
Create the client
Install the core package, then call createClient with the base URL of your API.
- npm
- yarn
- pnpm
npm install @hyper-fetch/core
yarn add @hyper-fetch/core
pnpm add @hyper-fetch/core
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",
});
The error generic is the global error: the error body your API returns, merged with each request's own error
type. See global error.
Create a request from it
client.createRequest defines one endpoint. It is called twice: the first call takes the types, the second the
options. Keep requests at module level and import them where you send them.
import { client } from "./client";
type User = { id: number; name: string };
export const getUser = client.createRequest<{ response: User }>()({
endpoint: "/users/:userId",
});
export const createUser = client.createRequest<{
response: User;
payload: { name: string };
}>()({
endpoint: "/users",
method: "POST",
});
method defaults to "GET". The fetching guide sends these requests.
Share one client per backend
Create the client once in its own module and import it everywhere. Requests inherit its auth, interceptors and defaults, and they share its cache and queues.
- One backend: one client, exported from
api/client.ts. - Several backends: one client each. Clients are isolated, so they never share cache, queues or interceptors.
- Tests: call
client.clear()between tests, see test isolation.
import { createClient } from "@hyper-fetch/core";
export const api = createClient({ url: "https://api.example.com" });
export const payments = createClient({ url: "https://payments.example.com" });
Configure the client
createClient takes the base url and factories for the modules. Most apps only set url.
| Option | Default | Use it to |
|---|---|---|
url | required | Set the base URL of every request |
mode | "auto" | Force "client" or "server" cache behavior |
cache | () => new Cache() | Add persistent storage, see persistence |
fetchDispatcher | () => new Dispatcher() | Configure the queue of GET and QUERY requests |
submitDispatcher | () => new Dispatcher() | Configure the queue of every other method |
appManager | () => new AppManager() | Change how focus and online state are detected |
The rest is set with methods on the client, chained after createClient:
export const client = createClient({ url: "https://api.example.com" })
.setDebug(process.env.NODE_ENV === "development")
.setLogLevel("debug")
.onAuth((request) =>
request.setHeaders({
...request.headers,
Authorization: `Bearer ${getToken()}`,
}),
);
- Defaults for every request:
client.adapter.setRequestDefaults, see global defaults. - Another transport:
client.setAdapter, see custom adapter and the Axios or GraphQL adapters. - Auth and interceptors: see authentication and intercepting.
You've set up the HyperFetch client.
- You can create a client with
createClientand type its global error. - You can create requests from it with
client.createRequest<Types>()(options). - You can share one client per backend and configure it with options and methods.
Runnable examples: Basic data fetching and Vanilla TypeScript.