# valifetch > Type-safe HTTP client built on native fetch with Valibot schema validation. Every page below is also available as plain Markdown (append `.md` to its URL); `llms-full.txt` bundles the whole site in one file. ## Docs ### Introduction - [Getting started](https://haihv.github.io/valifetch/guide/getting-started.md): Install valifetch and make your first type-safe, Valibot-validated request with native fetch in Node.js, Deno, Bun or the browser. - [Instances](https://haihv.github.io/valifetch/guide/instances.md): Create configured valifetch instances with create() and extend(): shared prefixUrl, headers, hooks and retry, with lightweight prototype-based inheritance. ### Making requests - [Requests](https://haihv.github.io/valifetch/guide/requests.md): Every valifetch request option: HTTP methods, json, form and raw bodies, path params, search params, headers, timeout, signals and download progress. - [Validation](https://haihv.github.io/valifetch/guide/validation.md): Validate response bodies, JSON request bodies, path params and search params with Valibot schemas, with full TypeScript type inference. - [Responses](https://haihv.github.io/valifetch/guide/responses.md): Choose how valifetch reads a response with responseType: JSON, text, Blob, ArrayBuffer, FormData, a stream, the raw Response, or server-sent events. - [Errors](https://haihv.github.io/valifetch/guide/errors.md): Handle valifetch failures with ValifetchError: typed codes for HTTP, validation, parse, timeout, abort and network errors, plus the parsed response body. - [Retry](https://haihv.github.io/valifetch/guide/retry.md): Configure valifetch retries: exponential backoff with jitter, status codes, methods, Retry-After handling, maxRetryAfter and a custom shouldRetry predicate. - [Hooks](https://haihv.github.io/valifetch/guide/hooks.md): Intercept the valifetch request lifecycle with beforeRequest, afterResponse, afterParseResponse, beforeRetry and beforeError hooks. - [Debug mode](https://haihv.github.io/valifetch/guide/debug.md): Turn on valifetch debug mode for structured request lifecycle logging, with sensitive headers and query parameters redacted automatically. ### Reference - [TypeScript](https://haihv.github.io/valifetch/guide/typescript.md): How valifetch infers TypeScript types from Valibot schemas, typed path params, and the public types exported from valifetch/types. - [Subpath imports and tree-shaking](https://haihv.github.io/valifetch/guide/subpath-imports.md): Import only what you need from valifetch, valifetch/auth, valifetch/mock, valifetch/error and valifetch/types for minimal, tree-shaken bundles. - [API design decisions](https://haihv.github.io/valifetch/guide/api-design-decisions.md): Why valifetch names and shapes its API the way it does: searchParams vs params, json/form/body, per-call responseType and positional hooks. - [Performance](https://haihv.github.io/valifetch/guide/performance.md): valifetch benchmark results against ky, ofetch and axios on Node.js 24, and the cost of schema validation. ### Project - [Versioning and stability](https://haihv.github.io/valifetch/guide/versioning.md): valifetch follows semantic versioning from 1.0.0: what counts as a breaking change, which defaults are covered, and how deprecations work. - [Security](https://haihv.github.io/valifetch/guide/security.md): valifetch security policy: supported versions, private vulnerability reporting and the threat model behind its hardening. ### Recipes - [Authentication](https://haihv.github.io/valifetch/recipes/auth.md): Add bearer token, HTTP basic or JWT refresh authentication to valifetch with the bearerAuth, basicAuth and jwtRefresh hooks from valifetch/auth. - [SSE and AI streaming](https://haihv.github.io/valifetch/recipes/sse-streaming.md): Consume server-sent events and AI token streams, such as OpenAI-style chat completions, with valifetch responseType sse as an async iterable. - [Mocking in tests](https://haihv.github.io/valifetch/recipes/testing.md): Mock valifetch requests in Vitest or Jest with createMock() from valifetch/mock: fixture responses, call inspection, no global fetch patching. - [Pagination](https://haihv.github.io/valifetch/recipes/pagination.md): Paginate APIs with valifetch: cursor-based and Link-header pagination with async generators, every page validated by a Valibot schema. - [Parallel requests](https://haihv.github.io/valifetch/recipes/parallel-requests.md): Run valifetch requests in parallel with all() and allSettled(): tuple-typed results and cancellation of the whole batch. - [File upload](https://haihv.github.io/valifetch/recipes/file-upload.md): Upload files with valifetch: multipart FormData, raw Blob, ArrayBuffer and ReadableStream bodies, and why fetch has no upload progress. ### Migration - [Migrating from ky](https://haihv.github.io/valifetch/migration/from-ky.md): Migrate from ky to valifetch: option and hook mapping for ky 1.x and 2.x, parsed-data return values and Valibot validation. - [Migrating from axios](https://haihv.github.io/valifetch/migration/from-axios.md): Migrate from axios to valifetch: native fetch instead of XHR, parsed bodies instead of response wrappers, interceptors to hooks, and validation. ### valifetch #### Classes - [Class: ValifetchError](https://haihv.github.io/api/index/classes/ValifetchError.md) #### Type Aliases - [Type Alias: AfterParseResponseHook\](https://haihv.github.io/api/index/type-aliases/AfterParseResponseHook.md) - [Type Alias: AfterResponseHook](https://haihv.github.io/api/index/type-aliases/AfterResponseHook.md) - [Type Alias: BeforeErrorHook](https://haihv.github.io/api/index/type-aliases/BeforeErrorHook.md) - [Type Alias: BeforeRequestHook](https://haihv.github.io/api/index/type-aliases/BeforeRequestHook.md) - [Type Alias: BeforeRetryHook](https://haihv.github.io/api/index/type-aliases/BeforeRetryHook.md) - [Type Alias: BeforeRetryState](https://haihv.github.io/api/index/type-aliases/BeforeRetryState.md) - [Type Alias: CallableInstance()](https://haihv.github.io/api/index/type-aliases/CallableInstance.md) - [Type Alias: CancellablePromise\](https://haihv.github.io/api/index/type-aliases/CancellablePromise.md) - [Type Alias: DebugEvent](https://haihv.github.io/api/index/type-aliases/DebugEvent.md) - [Type Alias: DebugOption](https://haihv.github.io/api/index/type-aliases/DebugOption.md) - [Type Alias: DownloadProgressEvent](https://haihv.github.io/api/index/type-aliases/DownloadProgressEvent.md) - [Type Alias: ErrorCode](https://haihv.github.io/api/index/type-aliases/ErrorCode.md) - [Type Alias: ExtractPathParams\](https://haihv.github.io/api/index/type-aliases/ExtractPathParams.md) - [Type Alias: GetOptions\](https://haihv.github.io/api/index/type-aliases/GetOptions.md) - [Type Alias: HasPathParams\](https://haihv.github.io/api/index/type-aliases/HasPathParams.md) - [Type Alias: Hooks](https://haihv.github.io/api/index/type-aliases/Hooks.md) - [Type Alias: HttpMethod](https://haihv.github.io/api/index/type-aliases/HttpMethod.md) - [Type Alias: InferResponseType\](https://haihv.github.io/api/index/type-aliases/InferResponseType.md) - [Type Alias: NormalizedOptions](https://haihv.github.io/api/index/type-aliases/NormalizedOptions.md) - [Type Alias: PathParamsRecord\](https://haihv.github.io/api/index/type-aliases/PathParamsRecord.md) - [Type Alias: PostOptions\](https://haihv.github.io/api/index/type-aliases/PostOptions.md) - [Type Alias: RawBody](https://haihv.github.io/api/index/type-aliases/RawBody.md) - [Type Alias: ResponseType](https://haihv.github.io/api/index/type-aliases/ResponseType.md) - [Type Alias: RetryContext](https://haihv.github.io/api/index/type-aliases/RetryContext.md) - [Type Alias: RetryOptions](https://haihv.github.io/api/index/type-aliases/RetryOptions.md) - [Type Alias: SearchParamsInit](https://haihv.github.io/api/index/type-aliases/SearchParamsInit.md) - [Type Alias: ValidationErrorInfo](https://haihv.github.io/api/index/type-aliases/ValidationErrorInfo.md) - [Type Alias: ValidationTarget](https://haihv.github.io/api/index/type-aliases/ValidationTarget.md) - [Type Alias: ValifetchBaseOptions](https://haihv.github.io/api/index/type-aliases/ValifetchBaseOptions.md) - [Type Alias: ValifetchErrorOptions](https://haihv.github.io/api/index/type-aliases/ValifetchErrorOptions.md) - [Type Alias: ValifetchInstance](https://haihv.github.io/api/index/type-aliases/ValifetchInstance.md) - [Type Alias: ValifetchInstanceOptions](https://haihv.github.io/api/index/type-aliases/ValifetchInstanceOptions.md) - [Type Alias: ValifetchOptions\](https://haihv.github.io/api/index/type-aliases/ValifetchOptions.md) #### Variables - [Variable: default](https://haihv.github.io/api/index/variables/default.md) - [Variable: stop](https://haihv.github.io/api/index/variables/stop.md) - [Variable: valifetch](https://haihv.github.io/api/index/variables/valifetch.md) ### valifetch/types #### Type Aliases - [Type Alias: MockCall](https://haihv.github.io/api/types/type-aliases/MockCall.md) - [Type Alias: MockHandler](https://haihv.github.io/api/types/type-aliases/MockHandler.md) - [Type Alias: ValifetchMock](https://haihv.github.io/api/types/type-aliases/ValifetchMock.md) ### valifetch/auth #### Type Aliases - [Type Alias: JwtRefreshOptions](https://haihv.github.io/api/auth/type-aliases/JwtRefreshOptions.md) #### Functions - [Function: basicAuth()](https://haihv.github.io/api/auth/functions/basicAuth.md) - [Function: bearerAuth()](https://haihv.github.io/api/auth/functions/bearerAuth.md) - [Function: jwtRefresh()](https://haihv.github.io/api/auth/functions/jwtRefresh.md) ### valifetch/mock #### Functions - [Function: createMock()](https://haihv.github.io/api/mock/functions/createMock.md) ### Other - [valifetch/error](https://haihv.github.io/valifetch/api/error.md) ## Installation ```bash npm install valifetch valibot # Deno deno add jsr:@haihv/valifetch # JSR subpaths: jsr:@haihv/valifetch/auth, jsr:@haihv/valifetch/mock ``` ## Core concept valifetch wraps native `fetch` with: - Automatic JSON parse (no `.json()` needed) - Valibot schema validation on request body, response, path params, and search params - Full TypeScript inference from schemas - Retry with exponential backoff + `Retry-After` header support, timeout, hooks, deduplication, download progress - SSE (`responseType: 'sse'`) — returns `AsyncIterable` with built-in SSE frame parsing; a single pending event over `sseMaxEventSize` (default 16 MiB of UTF-16 code units) cancels the stream and throws `PARSE_ERROR` (checked after each chunk; an event terminated within the same chunk is delivered whatever its size); `break`ing out of the loop cancels the response body - Security guarantees and caller responsibilities: see [SECURITY.md](https://github.com/haihv/valifetch/blob/main/SECURITY.md) ## Quick start ```typescript import valifetch from 'valifetch'; import * as v from 'valibot'; const UserSchema = v.object({ id: v.number(), name: v.string(), email: v.pipe(v.string(), v.email()) }); // GET — response type inferred from schema const user = await valifetch.get('https://api.example.com/users/1', { responseSchema: UserSchema }); // POST with body validation const newUser = await valifetch.post('https://api.example.com/users', { json: { name: 'John', email: 'john@example.com' }, bodySchema: v.object({ name: v.pipe(v.string(), v.minLength(1)), email: v.pipe(v.string(), v.email()) }), responseSchema: UserSchema, }); ``` ## Create a configured instance ```typescript const api = valifetch.create({ prefixUrl: 'https://api.example.com', timeout: 10_000, headers: { Authorization: 'Bearer token' }, retry: { limit: 3, statusCodes: [429, 500, 502, 503, 504] }, }); const user = await api.get('/users/1', { responseSchema: UserSchema }); ``` ```typescript // Custom retry predicate — true = retry, false = never, undefined = defer to // statusCodes + methods. Consulted for every failed response and network error, // before `beforeRetry`, always bounded by `limit`. May be async. const api = valifetch.create({ retry: { limit: 3, shouldRetry: async ({ reason, response }) => { if (reason === 'network') return true; // retry POSTs on network errors if (response.status === 409) { return (await response.clone().json()).code === 'STALE_VERSION'; } return undefined; }, }, }); ``` ## All HTTP methods ```typescript valifetch.get(url, options) // CancellablePromise valifetch.post(url, options) // CancellablePromise valifetch.put(url, options) // CancellablePromise valifetch.patch(url, options) // CancellablePromise valifetch.delete(url, options) // CancellablePromise valifetch.head(url, options) // CancellablePromise — no body; responseSchema is ignored valifetch.options(url, options) // CancellablePromise ``` ## Request bodies ```typescript // JSON — stringified, Content-Type: application/json, validated against bodySchema await api.post('/users', { json: { name: 'Ada' }, bodySchema: CreateUserSchema }); // Form — FormData → multipart/form-data; object/URLSearchParams → x-www-form-urlencoded await api.post('/login', { form: { username: 'ada', password: 'secret' } }); // Raw — sent as-is; set Content-Type yourself, no validation await api.put('/blobs/1', { body: new Blob([bytes]), headers: { 'content-type': 'application/octet-stream' }, }); // ReadableStream body — duplex: 'half' is added automatically; streams on Node 22+, Deno and Chromium over HTTP/2+; throws TypeError where the runtime cannot stream request bodies (Firefox; other engines vary) await api.put('/blobs/1', { body: fileStream, headers: { 'content-type': 'application/octet-stream' } }); ``` Exactly one of `json` / `form` / `body` per request — setting two or more throws a `TypeError`. ## Parallel requests ```typescript // all() — tuple of results, preserves element types, rejects on first failure const [user, posts] = await valifetch.all([ valifetch.get('/users/1', { responseSchema: UserSchema }), valifetch.get('/posts', { responseSchema: PostsSchema }), ]); // allSettled() — never rejects; standard PromiseSettledResult per request const results = await valifetch.allSettled([valifetch.get('/a'), valifetch.get('/b')]); // Both return a CancellablePromise; .cancel() aborts every cancellable input const batch = valifetch.all([valifetch.get('/a'), valifetch.get('/b')]); batch.cancel(); ``` ## Key options | Option | Type | Description | |---|---|---| | `responseSchema` | Valibot schema | Validate + type the response JSON | | `bodySchema` | Valibot schema | Validate `json` body before sending | | `paramsSchema` | Valibot schema | Validate `:param` path replacements | | `searchSchema` | Valibot schema | Validate query string params | | `json` | object | JSON body (auto-stringified); request-only, not on the bodyless methods (`get`/`head`/`delete`/`options`) | | `form` | FormData \| URLSearchParams \| Record\ | Form body (plain object values must be strings); request-only — removed from instance options, not on the bodyless methods (`get`/`head`/`delete`/`options`) | | `body` | `RawBody` = string \| Blob \| ArrayBuffer \| ArrayBufferView \| ReadableStream\ | Raw body sent as-is — no validation, no `Content-Type` inference; request-only, not on the bodyless methods (`get`/`head`/`delete`/`options`). Streams get `duplex: 'half'` automatically; streaming works on Node 22+, Deno and Chromium-based browsers over HTTP/2+; a `TypeError` is thrown where the runtime cannot stream request bodies (Firefox; other engines vary) | | `params` | object | Path param values for `:name` replacement; values are `encodeURIComponent`-encoded, own keys only, and `.` / `..` throw a `TypeError` | | `searchParams` | object \| URLSearchParams | Query string; instance value is a default, per-request value merges on top (request wins per key). Explicit `undefined`/`null` on a request key removes the instance default for that key. Instance defaults are appended to any query string already in the request path, not merged into it. | | `prefixUrl` | string | Base URL. The final URL always keeps the prefix origin and stays under the prefix path; `https://evil.com` / `//evil.com` inputs become path segments, and a `..` (or `%2e%2e`) path that climbs above the prefix throws a `TypeError`; a prefix containing `?` or `#` also throws a `TypeError` (use `searchParams`) | | `timeout` | number | Ms before TIMEOUT_ERROR (default: none — never times out; `0` also disables) | | `retry` | RetryOptions \| number \| false | Retry config — `{ limit, methods, statusCodes, delay, maxRetryAfter, shouldRetry(ctx) }` (defaults: `limit: 2`, `methods: ['GET','PUT','HEAD','DELETE','OPTIONS']`, `statusCodes: [408,413,429,500,502,503,504]`, `delay(attempt) = 0.3 * 2**attempt`s + 20% jitter, capped 30s, `maxRetryAfter: 60000` ms). Retry-After parsing is strict: all-digit seconds after trimming, or an HTTP-date (must contain a letter); anything else (`1.5`, `1e9`, `0x10`, `-1`) is ignored and `delay` backoff applies. If the requested delay exceeds `retry.maxRetryAfter` (default `60_000` ms; `Infinity` = no cap; non-number/`NaN`/negative → default), the request is NOT retried: it is handled as if retries were exhausted (`HTTP_ERROR` through `beforeError`, or returned with `throwHttpErrors: false`). That check runs after `shouldRetry` and before `beforeRetry`, so no `beforeRetry` hook or `retry` debug event fires. Retry sleeps are clamped to 0..2^31 − 1 ms (`NaN` → 0). A per-request or `extend()` `retry` value replaces the instance `retry` object entirely (no field merge), so restate `maxRetryAfter` when overriding. | | `responseType` | `'json'` \| `'text'` \| `'blob'` \| `'arrayBuffer'` \| `'formData'` \| `'stream'` \| `'raw'` \| `'sse'` | Response format; per-call only, not on `create()`/`extend()` | | `validateResponse` | boolean | Validate response against `responseSchema` (default: true) | | `validateRequest` | boolean | Validate body/params/search schemas (default: true) | | `throwHttpErrors` | boolean | Throw `HTTP_ERROR` on non-2xx status (default: true) | | `dedupe` | boolean | Deduplicate concurrent identical requests; key is method + fully-resolved URL (`prefixUrl` + path params + merged `searchParams`, from raw pre-validation values), scoped per instance (each no-arg `create()` gets its own cache). Excludes headers/body/schemas — don't enable for calls that differ only by header/body, and avoid on non-idempotent methods (default: false) | | `onDownloadProgress` | function | Progress callback `{ loaded, total, percent }`; not called for `responseType: 'stream' \| 'raw' \| 'sse'`; works at instance level too | | `priority` | `'high'` \| `'low'` \| `'auto'` | Forwarded to `fetch` unchanged | | `signal` | AbortSignal | Request-only — not on `create()`/`extend()` | | `debug` | `true` \| `(event: DebugEvent) => void` | Structured lifecycle logging (request, response, retry, cancel); `true` logs a summary with sensitive header and query-parameter values redacted | | `sseMaxEventSize` | number | Largest single pending SSE event buffered for `responseType: 'sse'`, in UTF-16 code units (default 16 MiB = 16777216; `Infinity` = no cap; non-number/`NaN`/negative → default). Allowed on `create()`/`extend()` and per call (per call wins) | | `hooks` | object | `beforeRequest`, `afterResponse`, `afterParseResponse`, `beforeRetry`, `beforeError` arrays | ## Design notes (intentional, locked) - `searchParams` (+ `searchSchema`) is the query option; `params` (+ `paramsSchema`) is the path option. `searchParams` mirrors `URL.searchParams` / ky — the stem mismatch with `searchSchema` is deliberate. - Three body options, exactly one per request: `json` (validated against `bodySchema`), `form`, or the raw `body` escape hatch (string / Blob / ArrayBuffer / typed array / ReadableStream) sent as-is with no validation and no `Content-Type` inference. Setting more than one throws a `TypeError` (not a `ValifetchError`). None is accepted at instance level. - `responseType` is per-call only (not on `create()`/`extend()`) because it changes the return type. - `ValifetchError.cause` is `unknown` (matches the standard `Error.cause`); any thrown value can be passed through. - Hook signatures are positional, following ky 1.x (ky 2 moved to state objects): `beforeRequest(request, options)`, `afterResponse(request, options, response)`, `afterParseResponse(data, response, request)`, `beforeRetry(state)`, `beforeError(error)` — not unified into one state object. A throwing hook propagates that error as-is (no `HOOK_ERROR` wrapping) and aborts the request. `beforeError` only ever sees `ValifetchError`s. - Entry-point rule: `valifetch` (`.`) exports the core runtime + core types; `valifetch/types` exports every public type (including `JwtRefreshOptions`, `MockCall`, `MockHandler`, `ValifetchMock`); `./error`, `./auth`, `./mock` are runtime subpaths. JSR publishes `.`, `./auth` and `./mock` (`jsr:@haihv/valifetch/auth`, `jsr:@haihv/valifetch/mock`); `./error` and `./types` are npm-only because they only re-export symbols already in `.`, `./auth` or `./mock`. - `options(url, requestOptions)` — the HTTP-verb method is named `options` deliberately; its parameter is internally named `requestOptions`. - `retry.shouldRetry(ctx)` receives `{ request, retryCount, reason, response | error }` (`reason: 'status'` → `response`, `'network'` → `error`, `retryCount` 1-based). Return `true` to retry even when `statusCodes`/`methods` would not, `false` to never retry this failure, `undefined` to defer to the built-in check. May be async; always bounded by `limit`; never consulted for an ok response; runs before `beforeRetry` (returning `false` skips those hooks); throwing aborts the request with that error. The context type is `RetryContext`, also the base of `BeforeRetryState`. - Counter semantics: `RetryOptions.delay(attempt)` is 0-based (`delay(0)` = first retry); `BeforeRetryState.retryCount` and a `DebugEvent` retry `attempt` are both 1-based ("the retry about to be performed"). ## Auth helpers (valifetch/auth) ```typescript import { bearerAuth, basicAuth, jwtRefresh } from 'valifetch/auth'; const api = valifetch.create({ hooks: { beforeRequest: [bearerAuth(() => getToken())] }, }); ``` ## Error handling ```typescript import { ValifetchError } from 'valifetch/error'; try { await api.get('/users/1', { responseSchema: UserSchema }); } catch (e) { if (e instanceof ValifetchError) { if (e.code === 'HTTP_ERROR') { console.log(e.status); // convenience getter for e.response?.status console.log(e.statusText); // convenience getter for e.response?.statusText console.log(e.responseBody); // parsed server error body — only populated on HTTP_ERROR (JSON object or plain text) } else if (e.code === 'VALIDATION_ERROR') { console.log(e.issues); // convenience getter for e.validation?.issues ?? [] console.log(e.target); // convenience getter for e.validation?.target: 'response' | 'body' | 'params' | 'search' console.log(e.validation?.input); // the invalid data that was validated // Request-side validation (target 'body' | 'params' | 'search') has e.request === undefined — // the Request doesn't exist yet at that point in the pipeline. } else if (e.code === 'TIMEOUT_ERROR') { // request exceeded timeout } else if (e.code === 'NETWORK_ERROR') { // fetch failed (offline, DNS, etc.) } else if (e.code === 'ABORT_ERROR') { // cancelled via .cancel() or AbortController } else if (e.code === 'PARSE_ERROR') { // Reading/parsing the response body failed — json, text, blob, arrayBuffer, or formData. // e.responseBody is the raw unparseable text (JSON reads only); e.cause is the raw thrown value. } // Boolean convenience: e.isHttpError, e.isValidationError, e.isTimeoutError, // e.isNetworkError, e.isAbortError, e.isParseError } } ``` | `ErrorCode` | Thrown when | Fields populated | |---|---|---| | `HTTP_ERROR` | non-2xx status, `throwHttpErrors: true` | `request`, `response`, `responseBody` | | `PARSE_ERROR` | body read/parse failed (json/text/blob/arrayBuffer/formData) | `request`, `response`, `cause`; `responseBody` (JSON reads only) | | `VALIDATION_ERROR` | Valibot schema failed | `validation: { target, issues, input }`; `request`/`response` only set when `target === 'response'` | | `TIMEOUT_ERROR` | `timeout` elapsed | `request`, `cause` | | `ABORT_ERROR` | `.cancel()` or signal abort | `request`, `cause` | | `NETWORK_ERROR` | `fetch` threw | `request`, `cause` | A `beforeRequest` hook may return a `Response` to bypass `fetch` entirely (e.g. `valifetch/mock`); that `Response` still flows through `afterResponse` hooks like a normal fetched response. ## Hooks: retry and error interception ```typescript import valifetch, { stop } from 'valifetch'; const api = valifetch.create({ hooks: { beforeRetry: [ // Return stop to abort retrying; return a new Request to replace for remaining attempts ({ request, response, retryCount }) => { // Give up early on a second 429 instead of waiting out the backoff if (retryCount > 1 && response?.status === 429) return stop; // Tag retried attempts so the server can detect duplicates return new Request(request, { headers: { ...Object.fromEntries(request.headers), 'x-retry-attempt': String(retryCount) }, }); }, ], beforeError: [ // Chain error transformations: each hook receives the error and must return it (mutated or replaced) (error) => { error.message = `[api] ${error.message}`; return error; }, ], }, }); ``` `beforeRetry`: returns `stop` (exported sentinel) to abort retrying and treat the original failure as final; a `Request` to replace the request for remaining attempts; or nothing to proceed with backoff. Hooks run in order; `stop` short-circuits remaining hooks. It only runs for failures that are retryable under your `retry` config (status codes / methods / limit) — a 401 never triggers it. A hook that throws aborts the request with that error. `beforeError`: receives `ValifetchError` and must return it — mutate and return the same instance, or return a replacement. Hooks chain (output becomes input for the next). ## Extend an instance ```typescript const adminApi = api.extend({ headers: { 'X-Admin': 'true' } }); // Dynamic extension const authApi = api.extend((opts) => ({ ...opts, headers: { ...opts.headers, Authorization: `Bearer ${getToken()}` }, })); ``` ## Callable syntax ```typescript const api = valifetch.create({ prefixUrl: 'https://api.example.com' }).callable(); const users = await api('/users'); // GET const user = await api('/users', { method: 'POST', json: { name: 'Jane' } }); ``` ## Debug mode `debug: true` logs a plain summary per event: `{ type, method, url, headers }` plus `attempt`/`status`/`responseHeaders` (response) or `attempt`/`delay`/`reason` (retry). Values of headers and of URL query parameters are replaced with `'[REDACTED]'` when the name contains (case-insensitive) `auth`, `cookie`, `token`, `secret`, `key`, `session`, `pass`, `credential`, `sig`, `jwt`, `dpop`, `csrf`, `xsrf`, `otp`, `bearer` or `code` — deliberately broad, so some harmless names are redacted too (e.g. `?access_token=S&X-Amz-Signature=S&code=S&page=2` logs only `page=2` unredacted). The live request is not modified; the URL path is logged as-is. A custom `debug` function receives the live, unredacted `Request`/`Response`, so redact before you log. ```typescript // debug: true → console.debug('[valifetch]', summary) for every lifecycle event const api = valifetch.create({ debug: true }); // debug: fn → custom handler, full type on DebugEvent import type { DebugEvent } from 'valifetch/types'; const api = valifetch.create({ debug: (event: DebugEvent) => { if (event.type === 'request') console.log('→', event.request.url); if (event.type === 'response') console.log('←', event.response.status, `attempt ${event.attempt}`); if (event.type === 'retry') console.log('↺', `delay ${event.delay}ms reason ${event.reason}`); if (event.type === 'cancel') console.log('✕', event.request.url); }, }); ``` `DebugEvent` discriminated union — `type` narrows the payload: `request` (+ `request`) | `response` (+ `request`, `attempt`) | `retry` (+ `request`, `attempt`, `delay`, `reason: 'status'|'network'`) | `cancel` (+ `request`). Child instances inherit `debug` from `extend()`; child value overrides parent. ## Testing (valifetch/mock) ```typescript import { createMock } from 'valifetch/mock'; const mock = createMock(); mock.get('/users').reply(200, [{ id: 1 }]); // permanent fixture mock.post('/users').replyOnce(201, { id: 2 }); // consumed once, then falls through mock.get('/users/:id').reply(200, { id: 1 }); // :param wildcard mock.get(/\/posts\/\d+$/).reply(200, {}); // RegExp (tested against full URL) mock.when('*', '/ping').reply(200, {}); // any method const api = valifetch.extend({ hooks: mock.hooks }); // attach await api.get('https://api.example.com/users'); const call = mock.lastCall(); // call.method, call.url, call.headers, call.body, call.searchParams mock.calls(); // all recorded calls mock.reset(); // clear between tests ``` Body values are always `JSON.stringify`-serialised. Omit body for a bodyless response. Null-body status codes (101, 204, 205, 304) always produce a bodyless response. Mock replies come from a `beforeRequest` hook outside the retry loop, so `retry` never retries a mocked response; each call consumes one queued reply. Unmatched requests fall through to the real `fetch`. ## Subpath exports ```typescript import valifetch from 'valifetch'; // main import { ValifetchError } from 'valifetch/error'; // error class only import { bearerAuth } from 'valifetch/auth'; // auth helpers import { createMock } from 'valifetch/mock'; // testing mock (test files only) import type { ValifetchOptions } from 'valifetch/types'; // types only, zero runtime ``` ## Performance (ops/sec, Node.js 24, fetch mocked) | Benchmark | valifetch | ky | axios | |---|---|---|---| | GET + JSON parse | 103,649 | 49,388 (2.1× slower) | 26,933 (3.9× slower) | | GET + schema validation | 90,743 | n/a | n/a | | POST JSON body | 73,777 | 22,881 (3.2× slower) | 22,318 (3.3× slower) | | 4xx error path | 35,792 | 27,038 (1.3× slower) | 11,666 (3.1× slower) | ## Versioning (semver from 1.0.0) - Major: removing/renaming any export of `.`, `./error`, `./types`, `./auth`, `./mock` (or a subpath); changing hook signatures/ordering; option renames or type changes that reject previously valid input; changing documented defaults (retry limit 2, retry statuses 408/413/429/500-504, `retry.maxRetryAfter` 60000 ms, `sseMaxEventSize` 16 MiB, `throwHttpErrors: true`, no default timeout); removing/renaming a `ValifetchError` code or changing which code a failure yields; changing HTTP method return types; raising the minimum Node.js (>=22) even if EOL; narrowing the valibot peer range (>=1.0.0). - Minor: new options/exports/hook types/subpaths; widening accepted input; new `ValifetchError` codes (keep a `default` branch when switching on `error.code`); stricter types that catch real runtime errors; raising the minimum TypeScript version (releases from the last ~2 years are supported). - Patch: bug fixes, perf, docs. Fixing behaviour that contradicted the docs is a patch. - Internal (not covered): undocumented APIs (e.g. the `opts`/`parent`/`merged` instance properties), `_`-prefixed names, `dist/` layout, error message wording (match `error.code`). - Deprecations: `@deprecated` JSDoc + CHANGELOG note at least one minor before removal in the next major. ## Links - npm: https://www.npmjs.com/package/valifetch - JSR: https://jsr.io/@haihv/valifetch - GitHub: https://github.com/haihv/valifetch - Documentation: https://haihv.github.io/valifetch/ - Docs index for agents: https://haihv.github.io/valifetch/llms.txt (every page as Markdown: append `.md` to its URL) - Full docs in one file: https://haihv.github.io/valifetch/llms-full.txt - Runnable browser demo: https://github.com/haihv/valifetch/tree/main/examples/demo (open in StackBlitz: https://stackblitz.com/github/haihv/valifetch/tree/main/examples/demo?file=src%2Fmain.ts) - Changelog: https://github.com/haihv/valifetch/blob/main/CHANGELOG.md