@alt-stack/http-client-fetch
v1.8.2
Published
Type-safe HTTP client using native fetch API
Readme
@alt-stack/http-client-fetch
Typed Zod-backed HTTP client using the standard Fetch API. Successful and documented error responses include the native Response as raw.
Install
pnpm add @alt-stack/http-client-fetch zodUse Zod 4 and a runtime with fetch, Response, Headers, and AbortController (Node.js 18+, modern browsers, or Bun).
Quick use
import { createApiClient } from "@alt-stack/http-client-fetch";
import { Request, Response } from "./generated-api.js";
const api = createApiClient({
baseUrl: "http://127.0.0.1:3000",
Request,
Response,
fetchOptions: { credentials: "include" },
});
const result = await api.get("/users/{id}", { params: { id: "u_1" } });
if (result.success) console.log(result.body, result.raw.status);Request and Response can be generated by @alt-stack/zod-openapi. Fetch options cannot override the executor-owned method, headers, body, or signal.
Custom fetch and auth headers
import { customFetch, getToken } from "./runtime.js";
const api = createApiClient({
baseUrl: "https://api.example.test",
Request,
Response,
fetch: customFetch,
headers: async () => ({ Authorization: `Bearer ${await getToken()}` }),
});
await api.get("/users/{id}", {
params: { id: "u_1" },
headers: { "X-Request-Id": "request-123" },
});Provide your own customFetch: typeof globalThis.fetch for proxies, platform polyfills, instrumentation, or tests. Both createApiClient and new FetchExecutor({ fetch: customFetch }) accept it. Without it, the executor reads globalThis.fetch at each attempt. The selected function is called without binding a receiver.
Client headers may be a static record or a sync/async provider. Providers run once per attempt, including retries, before request headers overlay them. Nullish values are omitted. Provider failures throw a sanitized UnexpectedApiClientError without retaining the original message or cause. See the core API for merge, retry, and timeout details.
