createFetch
Create configured fetch clients with shared base URLs, headers, query params, and throw behavior.
Use createFetch to configure shared defaults once and reuse them across requests.
Basic Usage
import { createFetch } from "@zap-studio/fetch";
const { api, $fetch } = createFetch({
baseURL: "https://api.example.com",
headers: {
Authorization: `Bearer ${token}`,
},
});
const user = await api.get("/users/1", UserSchema);
const health = await $fetch("/health");Each call uses the same overloads and error behavior as the top-level api and $fetch exports.
Options
| Option | Purpose |
|---|---|
baseURL | Prefix relative request URLs |
headers | Apply default headers to every request |
searchParams | Apply default query params to every request |
throwOnFetchError | Set default HTTP error behavior |
throwOnValidationError | Set default validation error behavior |
Base URL
Relative URLs are resolved against baseURL.
Absolute URLs keep their original origin.
const { api } = createFetch({
baseURL: "https://api.example.com",
});
await api.get("/users/1", UserSchema);
await api.get("https://status.example.com/health", StatusSchema);Headers
Default headers are merged with request headers. Request headers win when the same header is provided twice.
const { api } = createFetch({
headers: {
Authorization: `Bearer ${defaultToken}`,
},
});
await api.get("/users/1", UserSchema, {
headers: {
Authorization: `Bearer ${overrideToken}`,
},
});Search Params
Factory query params, URL query params, and request query params are merged in that order. Later values win.
const { api } = createFetch({
baseURL: "https://api.example.com",
searchParams: {
locale: "en",
page: "1",
},
});
await api.get("/users?page=2", UserListSchema, {
searchParams: {
q: "ada",
},
});The final request includes locale=en, page=2, and q=ada.
Default Throw Behavior
Set throw behavior once for a client and override it per request when needed.
const { api } = createFetch({
throwOnValidationError: false,
});
const result = await api.get("/users/1", UserSchema);
if (result.issues) {
console.error(result.issues);
}Edit on GitHub
Last updated on