@fetchkit/ffetch 5.4.1 → 5.4.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,394 +1,396 @@
1
- ![npm](https://img.shields.io/npm/v/@fetchkit/ffetch)
2
- ![Downloads](https://img.shields.io/npm/dm/@fetchkit/ffetch)
3
- ![GitHub stars](https://img.shields.io/github/stars/fetch-kit/ffetch?style=social)
4
-
5
- ![Build](https://github.com/fetch-kit/ffetch/actions/workflows/ci.yml/badge.svg)
6
- ![codecov](https://codecov.io/gh/fetch-kit/ffetch/branch/main/graph/badge.svg)
7
-
8
- ![MIT](https://img.shields.io/npm/l/@fetchkit/ffetch)
9
- ![bundlephobia](https://badgen.net/bundlephobia/minzip/@fetchkit/ffetch)
10
- ![Types](https://img.shields.io/npm/types/@fetchkit/ffetch)
11
-
12
- # @fetchkit/ffetch
13
-
14
- **A production-ready TypeScript-first drop-in replacement for native fetch, or any fetch-compatible implementation.**
15
-
16
- ffetch can wrap any fetch-compatible implementation (native fetch, node-fetch, undici, or framework-provided fetch), making it flexible for SSR, edge, and custom environments.
17
-
18
- ffetch uses a plugin architecture for optional features, so you only include what you need.
19
-
20
- ## Why ffetch
21
-
22
- - Keep native fetch ergonomics, add production safety (timeouts, retries, error strategy).
23
- - Keep your runtime flexibility (use global fetch or any fetch-compatible handler).
24
- - Keep your bundle lean – **~3kb minified** (optional plugins, zero runtime dependencies).
25
-
26
- ## Table of Contents
27
-
28
- - [@fetchkit/ffetch](#fetchkitffetch)
29
- - [Why ffetch](#why-ffetch)
30
- - [Table of Contents](#table-of-contents)
31
- - [Key Features](#key-features)
32
- - [Built-in Plugins at a Glance](#built-in-plugins-at-a-glance)
33
- - [What Problems Does ffetch Solve?](#what-problems-does-ffetch-solve)
34
- - [Quick Start](#quick-start)
35
- - [Install](#install)
36
- - [Basic Setup](#basic-setup)
37
- - [Production Setup with Plugins](#production-setup-with-plugins)
38
- - [Why not only native fetch?](#why-not-only-native-fetch)
39
- - [Common Recipes](#common-recipes)
40
- - [Using a Custom fetchHandler (SSR, metaframeworks, or polyfills)](#using-a-custom-fetchhandler-ssr-metaframeworks-or-polyfills)
41
- - [Advanced Example](#advanced-example)
42
- - [Custom Error Handling with `throwOnHttpError`](#custom-error-handling-with-throwonhttperror)
43
- - [Documentation](#documentation)
44
- - [Environment Requirements](#environment-requirements)
45
- - ["AbortSignal.any is not a function"](#abortsignalany-is-not-a-function)
46
- - [CDN Usage](#cdn-usage)
47
- - [Deduplication Limitations](#deduplication-limitations)
48
- - [Fetch vs. Axios vs. ky vs. `ffetch`](#fetch-vs-axios-vs-ky-vs-ffetch)
49
- - [Try ffetch in Action](#try-ffetch-in-action)
50
- - [Join the Community](#join-the-community)
51
- - [Contributing](#contributing)
52
- - [License](#license)
53
-
54
- ## Key Features
55
-
56
- - **Timeouts** – per-request or global
57
- - **Retries** – exponential backoff + jitter
58
- - **Abort-aware retries** – aborting during backoff cancels immediately
59
- - **Plugin architecture** – extensible lifecycle-based plugins for optional behavior
60
- - **Hooks** – logging, auth, metrics, request/response transformation
61
- - **Pending requests** – real-time monitoring of active requests
62
- - **Per-request overrides** – customize behavior on a per-request basis
63
- - **Universal** – Node.js, Browser, Cloudflare Workers, React Native
64
- - **Zero runtime deps** – ships as dual ESM/CJS
65
- - **Configurable error handling** – custom error types and `throwOnHttpError` flag to throw on HTTP errors
66
- - **Bulkhead plugin (optional, prebuilt)** – cap concurrency and queue depth per client instance
67
- - **Circuit breaker plugin (optional, prebuilt)** – automatic failure protection
68
- - **Hedge plugin (optional, prebuilt)** – race parallel attempts to reduce tail latency
69
- - **Context ID plugin (optional, prebuilt)** – inject a stable context ID header across retries/hedges for correlation
70
- - **Deduplication plugin (optional, prebuilt)** – automatic deduping of in-flight identical requests
71
- - **Request shortcuts plugin (optional, prebuilt)** – call `client.get(url)` / `.post()` / `.put()` / `.patch()` / `.delete()` directly on the client
72
- - **Response shortcuts plugin (optional, prebuilt)** – call `client(url).json()` / `.text()` / `.blob()` directly on the request promise
73
- - **Download progress plugin (optional, prebuilt)** – stream download progress callbacks with bytes transferred and percentage
74
-
75
- **Built-in error classes:** `TimeoutError`, `RetryLimitError`, `CircuitOpenError`, `BulkheadFullError`, `HttpError`, `NetworkError`, `AbortError`
76
-
77
- ### Built-in Plugins at a Glance
78
-
79
- All plugins are tree-shakeable — import only what you use.
80
-
81
- - **dedupePlugin (optional)**: dedupe in-flight identical requests.
82
- - **bulkheadPlugin (optional)**: cap in-flight concurrency with optional queue backpressure.
83
- - **hedgePlugin (optional)**: race multiple attempts and cancel losers when a winner is found.
84
- - **circuitPlugin (optional)**: fail fast after repeated failures.
85
- - **contextIdPlugin (optional)**: inject a stable request context ID (for example in `x-context-id`) across retries and hedges.
86
- - **requestShortcutsPlugin (optional)**: HTTP method shortcuts on the client (`.get()` / `.post()` / `.put()` / `.patch()` / `.delete()` / `.head()` / `.options()`).
87
- - **responseShortcutsPlugin (optional)**: use `client(url).json()` / `.text()` / `.blob()` style parsing.
88
- - **downloadProgressPlugin (optional)**: stream download progress via `onProgress(progress, chunk)` callback.
89
-
90
- ## What Problems Does ffetch Solve?
91
-
92
- ffetch is ideal for:
93
-
94
- - **Microservices and REST APIs** with retry requirements and timeout control
95
- - **High-traffic client applications** that need in-flight deduplication and circuit breaker protection
96
- - **SSR and metaframework apps** that require runtime flexibility (custom fetch handlers for different environments)
97
- - **Type-safe request handling** with strong TypeScript support and zero runtime dependencies
98
-
99
- ## Quick Start
100
-
101
- Migrating from v4? Start with the [migration guide](./docs/migration.md) before applying the examples below.
102
-
103
- ### Install
104
-
105
- ```bash
106
- # npm
107
- npm install @fetchkit/ffetch
108
-
109
- # yarn
110
- yarn add @fetchkit/ffetch
111
-
112
- # pnpm
113
- pnpm add @fetchkit/ffetch
114
-
115
- # bun
116
- bun add @fetchkit/ffetch
117
- ```
118
-
119
- ### Basic Setup
120
-
121
- ```typescript
122
- import { createClient } from '@fetchkit/ffetch'
123
-
124
- type User = { id: number; name: string }
125
-
126
- const api = createClient({ timeout: 5000, retries: 2 })
127
- const response = await api('https://api.example.com/users')
128
-
129
- if (!response.ok) {
130
- throw new Error(`Request failed: ${response.status}`)
131
- }
132
-
133
- const users = (await response.json()) as User[]
134
- ```
135
-
136
- ### Production Setup with Plugins
137
-
138
- ```typescript
139
- import { createClient } from '@fetchkit/ffetch'
140
- import { dedupePlugin } from '@fetchkit/ffetch/plugins/dedupe'
141
- import { circuitPlugin } from '@fetchkit/ffetch/plugins/circuit'
142
- import { contextIdPlugin } from '@fetchkit/ffetch/plugins/context-id'
143
- import { requestShortcutsPlugin } from '@fetchkit/ffetch/plugins/request-shortcuts'
144
- import { responseShortcutsPlugin } from '@fetchkit/ffetch/plugins/response-shortcuts'
145
-
146
- const api = createClient({
147
- timeout: 10_000,
148
- retries: 2,
149
- plugins: [
150
- // 1) Optional: dedupe identical in-flight requests
151
- dedupePlugin({ ttl: 30_000, sweepInterval: 5_000 }),
152
- // 2) Optional: open the circuit after repeated failures
153
- circuitPlugin({ threshold: 5, reset: 30_000 }),
154
- // 3) Optional: inject stable correlation context IDs
155
- contextIdPlugin(),
156
- // 4) Optional: enable request-promise parsing shortcuts
157
- responseShortcutsPlugin(),
158
- // 5) Optional: enable client HTTP method shortcuts
159
- requestShortcutsPlugin(),
160
- ],
161
- })
162
-
163
- const users = await api
164
- .get('https://api.example.com/users')
165
- .json<Array<{ id: number; name: string }>>()
166
-
167
- const p1 = api('https://api.example.com/data')
168
- const p2 = api('https://api.example.com/data')
169
- const [res1, res2] = await Promise.all([p1, p2])
170
- ```
171
-
172
- What this setup gives you:
173
-
174
- - **Operational safety**: retries with timeout defaults.
175
- - **Lower duplicate traffic (optional)**: concurrent identical requests share one in-flight call.
176
- - **Faster failure recovery (optional)**: circuit breaker blocks repeated failing calls.
177
- - **Better observability correlation (optional)**: stable request context IDs across retries and hedges.
178
- - **Cleaner request ergonomics (optional)**: `client.get(url)` / `.post(url, init)` style shortcuts.
179
- - **Cleaner parsing (optional)**: `client(url).json()` style shortcuts.
180
-
181
- ### Why not only native fetch?
182
-
183
- - Native fetch is a great baseline, but production apps usually need retries and timeout control.
184
- - ffetch keeps the fetch model and adds optional resilience features.
185
- - You can keep strict native behavior and only opt into plugins you need.
186
-
187
- ### Common Recipes
188
-
189
- ```typescript
190
- // Throw on non-2xx/429 once retries are exhausted
191
- const strict = createClient({ throwOnHttpError: true })
192
-
193
- // Use a custom fetch implementation (SSR/framework/runtime)
194
- import nodeFetch from 'node-fetch'
195
- const apiWithCustomHandler = createClient({ fetchHandler: nodeFetch })
196
-
197
- // Keep native Response flow (works with or without plugins)
198
- const plainApi = createClient({ timeout: 5000 })
199
- const response = await plainApi('https://api.example.com/health')
200
- const text = await response.text()
201
- ```
202
-
203
- ### Using a Custom fetchHandler (SSR, metaframeworks, or polyfills)
204
-
205
- ```typescript
206
- // Why this exists:
207
- // ffetch wraps whatever fetch-compatible function you provide.
208
- // This is useful when your runtime has a scoped/framework fetch,
209
- // or when Node needs an explicit fetch implementation.
210
-
211
- import { createClient } from '@fetchkit/ffetch'
212
- import nodeFetch from 'node-fetch'
213
-
214
- // Node.js example: provide node-fetch explicitly
215
- const apiNode = createClient({
216
- fetchHandler: nodeFetch,
217
- timeout: 5000,
218
- })
219
- const nodeResponse = await apiNode('https://api.example.com/data')
220
-
221
- // Framework example: pass the framework-scoped fetch
222
- // (e.g. the fetch passed into a request handler)
223
- async function loadData(frameworkFetch: typeof fetch) {
224
- const api = createClient({
225
- fetchHandler: frameworkFetch,
226
- timeout: 5000,
227
- })
228
-
229
- const response = await api('/internal/data')
230
- return response.json()
231
- }
232
- ```
233
-
234
- All ffetch features (timeouts, retries, plugins, hooks) behave the same with a custom `fetchHandler`.
235
-
236
- With `responseShortcutsPlugin()` enabled, request-promise shortcuts like `api(url).json()` also work the same.
237
-
238
- ### Advanced Example
239
-
240
- ```typescript
241
- // Production-ready client with error handling and monitoring
242
- import { createClient } from '@fetchkit/ffetch'
243
- import { dedupePlugin } from '@fetchkit/ffetch/plugins/dedupe'
244
- import { circuitPlugin } from '@fetchkit/ffetch/plugins/circuit'
245
-
246
- const client = createClient({
247
- timeout: 10000,
248
- retries: 2,
249
- fetchHandler: fetch, // Use custom fetch if needed
250
- plugins: [
251
- dedupePlugin({
252
- hashFn: (params) => `${params.method}|${params.url}|${params.body}`,
253
- ttl: 30_000,
254
- sweepInterval: 5_000,
255
- }),
256
- circuitPlugin({
257
- threshold: 5,
258
- reset: 30_000,
259
- onCircuitOpen: ({ request, reason }) =>
260
- console.warn('Circuit opened due to:', request.url, reason.type),
261
- onCircuitClose: ({ request, response }) =>
262
- console.info('Circuit closed after:', request.url, response.status),
263
- }),
264
- ],
265
- hooks: {
266
- before: async (req) => console.log('→', req.url),
267
- after: async (req, res) => console.log('←', res.status),
268
- onError: async (req, err) => console.error('Error:', err.message),
269
- },
270
- })
271
-
272
- try {
273
- const response = await client('/api/data')
274
-
275
- // Check HTTP status manually (like native fetch)
276
- if (!response.ok) {
277
- console.log('HTTP error:', response.status)
278
- return
279
- }
280
-
281
- const data = await response.json()
282
- console.log('Active requests:', client.pendingRequests.length)
283
- } catch (err) {
284
- if (err instanceof TimeoutError) {
285
- console.log('Request timed out')
286
- } else if (err instanceof RetryLimitError) {
287
- console.log('Request failed after retries')
288
- }
289
- }
290
- ```
291
-
292
- ### Custom Error Handling with `throwOnHttpError`
293
-
294
- Native `fetch`'s controversial behavior of not throwing errors for HTTP error status codes (4xx, 5xx) can lead to overlooked errors in applications. By default, `ffetch` follows this same pattern, returning a `Response` object regardless of the HTTP status code. However, with the `throwOnHttpError` flag, developers can configure `ffetch` to throw an `HttpError` for HTTP error responses, making error handling more explicit and robust. Note that this behavior is affected by retries and the circuit breaker - full details are explained in the [Error Handling documentation](./docs/errorhandling.md).
295
-
296
- ## Documentation
297
-
298
- | Topic | Description |
299
- | ------------------------------------------------------------ | ------------------------------------------------------------------------- |
300
- | **[Complete Documentation](./docs/index.md)** | **Start here** - Documentation index and overview |
301
- | **[API Reference](./docs/api.md)** | Complete API documentation and configuration options |
302
- | **[Plugin Architecture](./docs/plugins.md)** | Plugin lifecycle, custom plugin authoring, and integration patterns |
303
- | **[Deduplication](./docs/deduplication.md)** | How deduplication works, hash config, optional TTL cleanup, limitations |
304
- | **[Error Handling](./docs/errorhandling.md)** | Strategies for managing errors, including `throwOnHttpError` |
305
- | **[Advanced Features](./docs/advanced.md)** | Per-request overrides, pending requests, circuit breakers, custom errors |
306
- | **[Production Operations](./docs/production-operations.md)** | Pre-deploy checklist, alerting baseline, and incident playbook |
307
- | **[Hooks & Transformation](./docs/hooks.md)** | Lifecycle hooks, authentication, logging, request/response transformation |
308
- | **[Usage Examples](./docs/examples.md)** | Real-world patterns: REST clients, GraphQL, file uploads, microservices |
309
- | **[Compatibility](./docs/compatibility.md)** | Browser/Node.js support, polyfills, framework integration |
310
-
311
- ## Environment Requirements
312
-
313
- `ffetch` works best with native `AbortSignal.any` support:
314
-
315
- - **Node.js 20.6+** (native `AbortSignal.any`)
316
- - **Modern browsers with `AbortSignal.any`** (for example: Chrome 117+, Firefox 117+, Safari 17+, Edge 117+)
317
-
318
- If your environment does not support `AbortSignal.any` (Node.js < 20.6, older browsers), you can still use ffetch by installing an `AbortSignal.any` polyfill. `AbortSignal.timeout` is optional because ffetch includes an internal timeout fallback. See the [compatibility guide](./docs/compatibility.md) for instructions.
319
-
320
- **Custom fetch support:**
321
- You can pass any fetch-compatible implementation (native fetch, node-fetch, undici, SvelteKit, Next.js, Nuxt, or a polyfill) via the `fetchHandler` option. This makes ffetch fully compatible with SSR, edge, metaframework environments, custom backends, and test runners.
322
-
323
- #### "AbortSignal.any is not a function"
324
-
325
- Solution: Install a polyfill for `AbortSignal.any`
326
-
327
- ```bash
328
- npm install abort-controller-x
329
- ```
330
-
331
- ## CDN Usage
332
-
333
- ```html
334
- <script type="module">
335
- import { createClient } from 'https://unpkg.com/@fetchkit/ffetch/dist/index.min.js'
336
-
337
- const api = createClient({ timeout: 5000 })
338
- const data = await api('/api/data').then((r) => r.json())
339
- </script>
340
- ```
341
-
342
- ## Deduplication Limitations
343
-
344
- - Deduplication is **off** by default. Enable it via `plugins: [dedupePlugin()]`.
345
- - The default hash function is `dedupeRequestHash`, which handles common body types and skips deduplication for streams and FormData.
346
- - Optional stale-entry cleanup: `dedupePlugin({ ttl, sweepInterval })` enables map-entry eviction. TTL eviction only removes dedupe keys; it does not reject already in-flight promises.
347
- - **Stream bodies** (`ReadableStream`, `FormData`): Deduplication is skipped for requests with these body types, as they cannot be reliably hashed or replayed.
348
- - **Non-idempotent requests**: Use deduplication with caution for non-idempotent methods (e.g., POST), as it may suppress multiple intended requests.
349
- - **Custom hash function**: Ensure your hash function uniquely identifies requests to avoid accidental deduplication.
350
-
351
- See [deduplication.md](./docs/deduplication.md) for full details.
352
-
353
- ## Fetch vs. Axios vs. ky vs. `ffetch`
354
-
355
- | Feature | Native Fetch | Axios | ky | ffetch |
356
- | -------------------- | ------------------------------------------------------- | ------------------------------ | --------------------------------------------- | -------------------------------------------------------------------------------------- |
357
- | Timeouts | ❌ Manual AbortController | ✅ Built-in | ✅ Built-in | ✅ Built-in with fallbacks |
358
- | Retries | ❌ Manual implementation | ❌ Manual or plugins | ✅ Built-in | ✅ Smart exponential backoff |
359
- | Response Parsing DX | ⚠️ Response methods only (`await fetch(...).then(...)`) | ✅ `response.data` convenience | ✅ `.json()/.text()/.blob()` on request chain | ✅ Optional `responseShortcutsPlugin()` (`.json()/.text()/.blob()` on request chain) |
360
- | Plugin Architecture | ❌ Not available | ⚠️ Interceptors only | ⚠️ Hook-based extensions | ✅ First-class plugin pipeline (optional built-in + custom plugins) |
361
- | Circuit Breaker | ❌ Not available | ❌ Manual or plugins | ❌ Manual | ✅ Automatic failure protection |
362
- | Deduplication | ❌ Not available | ❌ Not available | ❌ Not available | ✅ Optional via `dedupePlugin()` |
363
- | Bulkheading | ❌ Not available | ❌ Not available | ❌ Not available | ✅ Optional via `bulkheadPlugin()` |
364
- | Request Hedging | ❌ Not available | ❌ Not available | ❌ Not available | ✅ Optional via `hedgePlugin()` (tail latency reduction) |
365
- | Request Monitoring | ❌ Manual tracking | ❌ Manual tracking | ❌ Manual tracking | ✅ Built-in pending requests |
366
- | Error Types | ❌ Generic errors | ⚠️ HTTP errors only | ✅ Specific error classes | ✅ Specific error classes |
367
- | TypeScript | ⚠️ Basic types | ⚠️ Basic types | ✅ Strong types | ✅ Full type safety |
368
- | Hooks/Middleware | ❌ Not available | ✅ Interceptors | ✅ Hooks | ✅ Comprehensive lifecycle hooks |
369
- | Bundle Size | ✅ Native (0kb) | ❌ ~13kb minified | ✅ Lightweight (fetch-based) | ✅ ~3kb minified |
370
- | Modern APIs | ✅ Web standards | ❌ XMLHttpRequest | ✅ Fetch + modern APIs | ✅ Fetch + modern features |
371
- | Download Progress | ❌ Manual ReadableStream | ❌ Manual | ✅ `onDownloadProgress` callback | ✅ Optional via `downloadProgressPlugin()` |
372
- | Custom Fetch Support | ❌ No (global only) | ❌ No | ❌ No | ✅ Yes (wrap any fetch-compatible implementation, including framework or custom fetch) |
373
-
374
- Note: built-in plugins in ffetch are opt-in. Use `bulkheadPlugin()` for concurrency isolation and backpressure, `dedupePlugin()` for deduplication, `circuitPlugin()` for circuit breaking, `hedgePlugin()` for tail-latency racing, `requestShortcutsPlugin()` for client HTTP method shortcuts, `responseShortcutsPlugin()` for request-promise parsing shortcuts, and `downloadProgressPlugin()` for streaming download progress. Bundle size: ~3kb core, additional optional plugin imports are tree-shakeable.
375
-
376
- ### Try ffetch in Action
377
-
378
- Want to see these clients in practice? Check out [ffetch-demo](https://github.com/fetch-kit/ffetch-demo) for working examples and side-by-side comparisons of how ffetch simplifies common fetch patterns.
379
-
380
- ## Join the Community
381
-
382
- Got questions, want to discuss features, or share examples? Join the **Fetch-Kit Discord server**:
383
-
384
- [![Discord](https://img.shields.io/badge/Discord-Join_Fetch--Kit-7289DA?logo=discord&logoColor=white)](https://discord.gg/sdyPBPCDUg)
385
-
386
- ## Contributing
387
-
388
- - **Issues**: [GitHub Issues](https://github.com/fetch-kit/ffetch/issues)
389
- - **Pull Requests**: [GitHub PRs](https://github.com/fetch-kit/ffetch/pulls)
390
- - **Documentation**: Found in `./docs/` - PRs welcome!
391
-
392
- ## License
393
-
394
- MIT © 2025 gkoos
1
+ ![npm](https://img.shields.io/npm/v/@fetchkit/ffetch)
2
+ ![Downloads](https://img.shields.io/npm/dm/@fetchkit/ffetch)
3
+ ![GitHub stars](https://img.shields.io/github/stars/fetch-kit/ffetch?style=social)
4
+
5
+ ![Build](https://github.com/fetch-kit/ffetch/actions/workflows/ci.yml/badge.svg)
6
+ ![codecov](https://codecov.io/gh/fetch-kit/ffetch/branch/main/graph/badge.svg)
7
+
8
+ ![MIT](https://img.shields.io/npm/l/@fetchkit/ffetch)
9
+ ![bundlephobia](https://badgen.net/bundlephobia/minzip/@fetchkit/ffetch)
10
+ ![Types](https://img.shields.io/npm/types/@fetchkit/ffetch)
11
+
12
+ # @fetchkit/ffetch
13
+
14
+ **A production-ready TypeScript-first drop-in replacement for native fetch, or any fetch-compatible implementation.**
15
+
16
+ ffetch can wrap any fetch-compatible implementation (native fetch, node-fetch, undici, or framework-provided fetch), making it flexible for SSR, edge, and custom environments.
17
+
18
+ ffetch uses a plugin architecture for optional features, so you only include what you need.
19
+
20
+ ## Why ffetch
21
+
22
+ - Keep native fetch ergonomics, add production safety (timeouts, retries, error strategy).
23
+ - Keep your runtime flexibility (use global fetch or any fetch-compatible handler).
24
+ - Keep your bundle lean – **~3kb minified** (optional plugins, zero runtime dependencies).
25
+
26
+ ## Table of Contents
27
+
28
+ - [@fetchkit/ffetch](#fetchkitffetch)
29
+ - [Why ffetch](#why-ffetch)
30
+ - [Table of Contents](#table-of-contents)
31
+ - [Key Features](#key-features)
32
+ - [Built-in Plugins at a Glance](#built-in-plugins-at-a-glance)
33
+ - [What Problems Does ffetch Solve?](#what-problems-does-ffetch-solve)
34
+ - [Quick Start](#quick-start)
35
+ - [Install](#install)
36
+ - [Basic Setup](#basic-setup)
37
+ - [Production Setup with Plugins](#production-setup-with-plugins)
38
+ - [Why not only native fetch?](#why-not-only-native-fetch)
39
+ - [Common Recipes](#common-recipes)
40
+ - [Using a Custom fetchHandler (SSR, metaframeworks, or polyfills)](#using-a-custom-fetchhandler-ssr-metaframeworks-or-polyfills)
41
+ - [Advanced Example](#advanced-example)
42
+ - [Custom Error Handling with `throwOnHttpError`](#custom-error-handling-with-throwonhttperror)
43
+ - [Documentation](#documentation)
44
+ - [Environment Requirements](#environment-requirements)
45
+ - ["AbortSignal.any is not a function"](#abortsignalany-is-not-a-function)
46
+ - [CDN Usage](#cdn-usage)
47
+ - [Deduplication Limitations](#deduplication-limitations)
48
+ - [Fetch vs. Axios vs. ky vs. `ffetch`](#fetch-vs-axios-vs-ky-vs-ffetch)
49
+ - [Try ffetch in Action](#try-ffetch-in-action)
50
+ - [Join the Community](#join-the-community)
51
+ - [Contributing](#contributing)
52
+ - [License](#license)
53
+
54
+ ## Key Features
55
+
56
+ - **Timeouts** – per-request or global
57
+ - **Retries** – exponential backoff + jitter
58
+ - **Abort-aware retries** – aborting during backoff cancels immediately
59
+ - **Plugin architecture** – extensible lifecycle-based plugins for optional behavior
60
+ - **Hooks** – logging, auth, metrics, request/response transformation
61
+ - **Pending requests** – real-time monitoring of active requests
62
+ - **Per-request overrides** – customize behavior on a per-request basis
63
+ - **Universal** – Node.js, Browser, Cloudflare Workers, React Native
64
+ - **Zero runtime deps** – ships as dual ESM/CJS
65
+ - **Configurable error handling** – custom error types and `throwOnHttpError` flag to throw on HTTP errors
66
+ - **Bulkhead plugin (optional, prebuilt)** – cap concurrency and queue depth per client instance
67
+ - **Circuit breaker plugin (optional, prebuilt)** – automatic failure protection
68
+ - **Hedge plugin (optional, prebuilt)** – race parallel attempts to reduce tail latency
69
+ - **Context ID plugin (optional, prebuilt)** – inject a stable context ID header across retries/hedges for correlation
70
+ - **Deduplication plugin (optional, prebuilt)** – automatic deduping of in-flight identical requests
71
+ - **Request shortcuts plugin (optional, prebuilt)** – call `client.get(url)` / `.post()` / `.put()` / `.patch()` / `.delete()` directly on the client
72
+ - **Response shortcuts plugin (optional, prebuilt)** – call `client(url).json()` / `.text()` / `.blob()` directly on the request promise
73
+ - **Download progress plugin (optional, prebuilt)** – stream download progress callbacks with bytes transferred and percentage
74
+
75
+ **Built-in error classes:** `TimeoutError`, `RetryLimitError`, `CircuitOpenError`, `BulkheadFullError`, `HttpError`, `NetworkError`, `AbortError`
76
+
77
+ ### Built-in Plugins at a Glance
78
+
79
+ All plugins are tree-shakeable — import only what you use.
80
+
81
+ - **dedupePlugin (optional)**: dedupe in-flight identical requests.
82
+ - **bulkheadPlugin (optional)**: cap in-flight concurrency with optional queue backpressure.
83
+ - **hedgePlugin (optional)**: race multiple attempts and cancel losers when a winner is found.
84
+ - **circuitPlugin (optional)**: fail fast after repeated failures.
85
+ - **contextIdPlugin (optional)**: inject a stable request context ID (for example in `x-context-id`) across retries and hedges.
86
+ - **requestShortcutsPlugin (optional)**: HTTP method shortcuts on the client (`.get()` / `.post()` / `.put()` / `.patch()` / `.delete()` / `.head()` / `.options()`).
87
+ - **responseShortcutsPlugin (optional)**: use `client(url).json()` / `.text()` / `.blob()` style parsing.
88
+ - **downloadProgressPlugin (optional)**: stream download progress via `onProgress(progress, chunk)` callback.
89
+
90
+ ## What Problems Does ffetch Solve?
91
+
92
+ ffetch is ideal for:
93
+
94
+ - **Microservices and REST APIs** with retry requirements and timeout control
95
+ - **High-traffic client applications** that need in-flight deduplication and circuit breaker protection
96
+ - **SSR and metaframework apps** that require runtime flexibility (custom fetch handlers for different environments)
97
+ - **Type-safe request handling** with strong TypeScript support and zero runtime dependencies
98
+
99
+ ## Quick Start
100
+
101
+ Migrating from v4? Start with the [migration guide](./docs/migration.md) before applying the examples below.
102
+
103
+ ### Install
104
+
105
+ ```bash
106
+ # npm
107
+ npm install @fetchkit/ffetch
108
+
109
+ # yarn
110
+ yarn add @fetchkit/ffetch
111
+
112
+ # pnpm
113
+ pnpm add @fetchkit/ffetch
114
+
115
+ # bun
116
+ bun add @fetchkit/ffetch
117
+ ```
118
+
119
+ ### Basic Setup
120
+
121
+ ```typescript
122
+ import { createClient } from '@fetchkit/ffetch'
123
+
124
+ type User = { id: number; name: string }
125
+
126
+ const api = createClient({ timeout: 5000, retries: 2 })
127
+ const response = await api('https://api.example.com/users')
128
+
129
+ if (!response.ok) {
130
+ throw new Error(`Request failed: ${response.status}`)
131
+ }
132
+
133
+ const users = (await response.json()) as User[]
134
+ ```
135
+
136
+ ### Production Setup with Plugins
137
+
138
+ ```typescript
139
+ import { createClient } from '@fetchkit/ffetch'
140
+ import { dedupePlugin } from '@fetchkit/ffetch/plugins/dedupe'
141
+ import { circuitPlugin } from '@fetchkit/ffetch/plugins/circuit'
142
+ import { contextIdPlugin } from '@fetchkit/ffetch/plugins/context-id'
143
+ import { requestShortcutsPlugin } from '@fetchkit/ffetch/plugins/request-shortcuts'
144
+ import { responseShortcutsPlugin } from '@fetchkit/ffetch/plugins/response-shortcuts'
145
+
146
+ const api = createClient({
147
+ timeout: 10_000,
148
+ retries: 2,
149
+ plugins: [
150
+ // 1) Optional: dedupe identical in-flight requests
151
+ dedupePlugin({ ttl: 30_000, sweepInterval: 5_000 }),
152
+ // 2) Optional: open the circuit after repeated failures
153
+ circuitPlugin({ threshold: 5, reset: 30_000 }),
154
+ // 3) Optional: inject stable correlation context IDs
155
+ contextIdPlugin(),
156
+ // 4) Optional: enable request-promise parsing shortcuts
157
+ responseShortcutsPlugin(),
158
+ // 5) Optional: enable client HTTP method shortcuts
159
+ requestShortcutsPlugin(),
160
+ ],
161
+ })
162
+
163
+ const users = await api
164
+ .get('https://api.example.com/users')
165
+ .json<Array<{ id: number; name: string }>>()
166
+
167
+ const p1 = api('https://api.example.com/data')
168
+ const p2 = api('https://api.example.com/data')
169
+ const [res1, res2] = await Promise.all([p1, p2])
170
+ ```
171
+
172
+ What this setup gives you:
173
+
174
+ - **Operational safety**: retries with timeout defaults.
175
+ - **Lower duplicate traffic (optional)**: concurrent identical requests share one in-flight call.
176
+ - **Faster failure recovery (optional)**: circuit breaker blocks repeated failing calls.
177
+ - **Better observability correlation (optional)**: stable request context IDs across retries and hedges.
178
+ - **Cleaner request ergonomics (optional)**: `client.get(url)` / `.post(url, init)` style shortcuts.
179
+ - **Cleaner parsing (optional)**: `client(url).json()` style shortcuts.
180
+
181
+ ### Why not only native fetch?
182
+
183
+ - Native fetch is a great baseline, but production apps usually need retries and timeout control.
184
+ - ffetch keeps the fetch model and adds optional resilience features.
185
+ - You can keep strict native behavior and only opt into plugins you need.
186
+
187
+ ### Common Recipes
188
+
189
+ ```typescript
190
+ // Throw on non-2xx/429 once retries are exhausted
191
+ const strict = createClient({ throwOnHttpError: true })
192
+
193
+ // Use a custom fetch implementation (SSR/framework/runtime)
194
+ import nodeFetch from 'node-fetch'
195
+ const apiWithCustomHandler = createClient({ fetchHandler: nodeFetch })
196
+
197
+ // Keep native Response flow (works with or without plugins)
198
+ const plainApi = createClient({ timeout: 5000 })
199
+ const response = await plainApi('https://api.example.com/health')
200
+ const text = await response.text()
201
+ ```
202
+
203
+ ### Using a Custom fetchHandler (SSR, metaframeworks, or polyfills)
204
+
205
+ ```typescript
206
+ // Why this exists:
207
+ // ffetch wraps whatever fetch-compatible function you provide.
208
+ // This is useful when your runtime has a scoped/framework fetch,
209
+ // or when Node needs an explicit fetch implementation.
210
+
211
+ import { createClient } from '@fetchkit/ffetch'
212
+ import nodeFetch from 'node-fetch'
213
+
214
+ // Node.js example: provide node-fetch explicitly
215
+ const apiNode = createClient({
216
+ fetchHandler: nodeFetch,
217
+ timeout: 5000,
218
+ })
219
+ const nodeResponse = await apiNode('https://api.example.com/data')
220
+
221
+ // Framework example: pass the framework-scoped fetch
222
+ // (e.g. the fetch passed into a request handler)
223
+ async function loadData(frameworkFetch: typeof fetch) {
224
+ const api = createClient({
225
+ fetchHandler: frameworkFetch,
226
+ timeout: 5000,
227
+ })
228
+
229
+ const response = await api('/internal/data')
230
+ return response.json()
231
+ }
232
+ ```
233
+
234
+ All ffetch features (timeouts, retries, plugins, hooks) behave the same with a custom `fetchHandler`.
235
+
236
+ With `responseShortcutsPlugin()` enabled, request-promise shortcuts like `api(url).json()` also work the same.
237
+
238
+ ### Advanced Example
239
+
240
+ ```typescript
241
+ // Production-ready client with error handling and monitoring
242
+ import { createClient } from '@fetchkit/ffetch'
243
+ import { dedupePlugin } from '@fetchkit/ffetch/plugins/dedupe'
244
+ import { circuitPlugin } from '@fetchkit/ffetch/plugins/circuit'
245
+
246
+ const client = createClient({
247
+ timeout: 10000,
248
+ retries: 2,
249
+ fetchHandler: fetch, // Use custom fetch if needed
250
+ plugins: [
251
+ dedupePlugin({
252
+ hashFn: (params) => `${params.method}|${params.url}|${params.body}`,
253
+ ttl: 30_000,
254
+ sweepInterval: 5_000,
255
+ }),
256
+ circuitPlugin({
257
+ threshold: 5,
258
+ reset: 30_000,
259
+ onCircuitOpen: ({ request, reason }) =>
260
+ console.warn('Circuit opened due to:', request.url, reason.type),
261
+ onCircuitClose: ({ request, response }) =>
262
+ console.info('Circuit closed after:', request.url, response.status),
263
+ }),
264
+ ],
265
+ hooks: {
266
+ before: async (req) => console.log('→', req.url),
267
+ after: async (req, res) => console.log('←', res.status),
268
+ onError: async (req, err) => console.error('Error:', err.message),
269
+ },
270
+ })
271
+
272
+ try {
273
+ const response = await client('/api/data')
274
+
275
+ // Check HTTP status manually (like native fetch)
276
+ if (!response.ok) {
277
+ console.log('HTTP error:', response.status)
278
+ return
279
+ }
280
+
281
+ const data = await response.json()
282
+ console.log('Active requests:', client.pendingRequests.length)
283
+ } catch (err) {
284
+ if (err instanceof TimeoutError) {
285
+ console.log('Request timed out')
286
+ } else if (err instanceof RetryLimitError) {
287
+ console.log('Request failed after retries')
288
+ }
289
+ }
290
+ ```
291
+
292
+ ### Custom Error Handling with `throwOnHttpError`
293
+
294
+ Native `fetch`'s controversial behavior of not throwing errors for HTTP error status codes (4xx, 5xx) can lead to overlooked errors in applications. By default, `ffetch` follows this same pattern, returning a `Response` object regardless of the HTTP status code. However, with the `throwOnHttpError` flag, developers can configure `ffetch` to throw an `HttpError` for HTTP error responses, making error handling more explicit and robust. Note that this behavior is affected by retries and the circuit breaker - full details are explained in the [Error Handling documentation](./docs/errorhandling.md).
295
+
296
+ ## Documentation
297
+
298
+ | Topic | Description |
299
+ | ------------------------------------------------------------ | ------------------------------------------------------------------------- |
300
+ | **[Complete Documentation](./docs/index.md)** | **Start here** - Documentation index and overview |
301
+ | **[API Reference](./docs/api.md)** | Complete API documentation and configuration options |
302
+ | **[Plugin Architecture](./docs/plugins.md)** | Plugin lifecycle, custom plugin authoring, and integration patterns |
303
+ | **[Deduplication](./docs/deduplication.md)** | How deduplication works, hash config, optional TTL cleanup, limitations |
304
+ | **[Error Handling](./docs/errorhandling.md)** | Strategies for managing errors, including `throwOnHttpError` |
305
+ | **[Advanced Features](./docs/advanced.md)** | Per-request overrides, pending requests, circuit breakers, custom errors |
306
+ | **[Production Operations](./docs/production-operations.md)** | Pre-deploy checklist, alerting baseline, and incident playbook |
307
+ | **[Hooks & Transformation](./docs/hooks.md)** | Lifecycle hooks, authentication, logging, request/response transformation |
308
+ | **[Usage Examples](./docs/examples.md)** | Real-world patterns: REST clients, GraphQL, file uploads, microservices |
309
+ | **[Compatibility](./docs/compatibility.md)** | Browser/Node.js support, polyfills, framework integration |
310
+
311
+ ## Environment Requirements
312
+
313
+ `ffetch` works best with native `AbortSignal.any` support:
314
+
315
+ - **Node.js 20.6+** (native `AbortSignal.any`)
316
+ - **Modern browsers with `AbortSignal.any`** (for example: Chrome 117+, Firefox 117+, Safari 17+, Edge 117+)
317
+
318
+ If your environment does not support `AbortSignal.any` (Node.js < 20.6, older browsers), you can still use ffetch by installing an `AbortSignal.any` polyfill. `AbortSignal.timeout` is optional because ffetch includes an internal timeout fallback. See the [compatibility guide](./docs/compatibility.md) for instructions.
319
+
320
+ **Custom fetch support:**
321
+ You can pass any fetch-compatible implementation (native fetch, node-fetch, undici, SvelteKit, Next.js, Nuxt, or a polyfill) via the `fetchHandler` option. This makes ffetch fully compatible with SSR, edge, metaframework environments, custom backends, and test runners.
322
+
323
+ #### "AbortSignal.any is not a function"
324
+
325
+ Solution: Install a polyfill for `AbortSignal.any`
326
+
327
+ ```bash
328
+ npm install abort-controller-x
329
+ ```
330
+
331
+ ## CDN Usage
332
+
333
+ ```html
334
+ <script type="module">
335
+ import { createClient } from 'https://unpkg.com/@fetchkit/ffetch/dist/index.min.js'
336
+
337
+ const api = createClient({ timeout: 5000 })
338
+ const data = await api('/api/data').then((r) => r.json())
339
+ </script>
340
+ ```
341
+
342
+ ## Deduplication Limitations
343
+
344
+ - Deduplication is **off** by default. Enable it via `plugins: [dedupePlugin()]`.
345
+ - The default hash function is `dedupeRequestHash`, which handles common body types and skips deduplication for streams and FormData.
346
+ - Optional stale-entry cleanup: `dedupePlugin({ ttl, sweepInterval })` enables map-entry eviction. TTL eviction only removes dedupe keys; it does not reject already in-flight promises.
347
+ - **Stream bodies** (`ReadableStream`, `FormData`): Deduplication is skipped for requests with these body types, as they cannot be reliably hashed or replayed.
348
+ - **Non-idempotent requests**: Use deduplication with caution for non-idempotent methods (e.g., POST), as it may suppress multiple intended requests.
349
+ - **Custom hash function**: Ensure your hash function uniquely identifies requests to avoid accidental deduplication.
350
+
351
+ See [deduplication.md](./docs/deduplication.md) for full details.
352
+
353
+ ## Fetch vs. Axios vs. ky vs. `ffetch`
354
+
355
+ | Feature | Native Fetch | Axios | ky | ffetch |
356
+ | -------------------- | ------------------------------------------------------- | ------------------------------ | --------------------------------------------- | -------------------------------------------------------------------------------------- |
357
+ | Timeouts | ❌ Manual AbortController | ✅ Built-in | ✅ Built-in | ✅ Built-in with fallbacks |
358
+ | Retries | ❌ Manual implementation | ❌ Manual or plugins | ✅ Built-in | ✅ Smart exponential backoff |
359
+ | Response Parsing DX | ⚠️ Response methods only (`await fetch(...).then(...)`) | ✅ `response.data` convenience | ✅ `.json()/.text()/.blob()` on request chain | ✅ Optional `responseShortcutsPlugin()` (`.json()/.text()/.blob()` on request chain) |
360
+ | Plugin Architecture | ❌ Not available | ⚠️ Interceptors only | ⚠️ Hook-based extensions | ✅ First-class plugin pipeline (optional built-in + custom plugins) |
361
+ | Circuit Breaker | ❌ Not available | ❌ Manual or plugins | ❌ Manual | ✅ Automatic failure protection |
362
+ | Deduplication | ❌ Not available | ❌ Not available | ❌ Not available | ✅ Optional via `dedupePlugin()` |
363
+ | Bulkheading | ❌ Not available | ❌ Not available | ❌ Not available | ✅ Optional via `bulkheadPlugin()` |
364
+ | Request Hedging | ❌ Not available | ❌ Not available | ❌ Not available | ✅ Optional via `hedgePlugin()` (tail latency reduction) |
365
+ | Request Monitoring | ❌ Manual tracking | ❌ Manual tracking | ❌ Manual tracking | ✅ Built-in pending requests |
366
+ | Error Types | ❌ Generic errors | ⚠️ HTTP errors only | ✅ Specific error classes | ✅ Specific error classes |
367
+ | TypeScript | ⚠️ Basic types | ⚠️ Basic types | ✅ Strong types | ✅ Full type safety |
368
+ | Hooks/Middleware | ❌ Not available | ✅ Interceptors | ✅ Hooks | ✅ Comprehensive lifecycle hooks |
369
+ | Bundle Size | ✅ Native (0kb) | ❌ ~13kb minified | ✅ Lightweight (fetch-based) | ✅ ~3kb minified |
370
+ | Modern APIs | ✅ Web standards | ❌ XMLHttpRequest | ✅ Fetch + modern APIs | ✅ Fetch + modern features |
371
+ | Download Progress | ❌ Manual ReadableStream | ❌ Manual | ✅ `onDownloadProgress` callback | ✅ Optional via `downloadProgressPlugin()` |
372
+ | Custom Fetch Support | ❌ No (global only) | ❌ No | ❌ No | ✅ Yes (wrap any fetch-compatible implementation, including framework or custom fetch) |
373
+
374
+ Note: built-in plugins in ffetch are opt-in. Use `bulkheadPlugin()` for concurrency isolation and backpressure, `dedupePlugin()` for deduplication, `circuitPlugin()` for circuit breaking, `hedgePlugin()` for tail-latency racing, `requestShortcutsPlugin()` for client HTTP method shortcuts, `responseShortcutsPlugin()` for request-promise parsing shortcuts, and `downloadProgressPlugin()` for streaming download progress. Bundle size: ~3kb core, additional optional plugin imports are tree-shakeable.
375
+
376
+ ## Try ffetch in Action
377
+
378
+ Want to see these clients in practice? Check out [ffetch-demo](https://github.com/fetch-kit/ffetch-demo) for working examples and side-by-side comparisons of how ffetch simplifies common fetch patterns.
379
+
380
+ 📰 Featured in [Node Weekly #594](https://nodeweekly.com/issues/594)
381
+
382
+ ## Join the Community
383
+
384
+ Got questions, want to discuss features, or share examples? Join the **Fetch-Kit Discord server**:
385
+
386
+ [![Discord](https://img.shields.io/badge/Discord-Join_Fetch--Kit-7289DA?logo=discord&logoColor=white)](https://discord.gg/sdyPBPCDUg)
387
+
388
+ ## Contributing
389
+
390
+ - **Issues**: [GitHub Issues](https://github.com/fetch-kit/ffetch/issues)
391
+ - **Pull Requests**: [GitHub PRs](https://github.com/fetch-kit/ffetch/pulls)
392
+ - **Documentation**: Found in `./docs/` - PRs welcome!
393
+
394
+ ## License
395
+
396
+ MIT © 2025- gkoos