nuxt-custom-fetch 4.5.0 → 4.6.1

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
@@ -14,9 +14,11 @@ Use `CustomFetch` when you specifically need an extra request layer on top of th
14
14
 
15
15
  ## Compatibility
16
16
 
17
- - `v4`: Nuxt `>= 4.5.0`
17
+ - `v4`: Nuxt `^4.5.0` (Nuxt 4 only)
18
18
  - `v2`: Nuxt `3.0.0` to `3.16.x`
19
19
 
20
+ The development playground targets Nuxt `4.7.0` and Vue `3.5.46`. Nuxt `4.7.0` requires Node.js `^22.22.3 || ^24.15.0 || >=26.0.0`.
21
+
20
22
  ## Current Maintenance Summary
21
23
 
22
24
  The current implementation is maintained around these guarantees:
@@ -25,9 +27,11 @@ The current implementation is maintained around these guarantees:
25
27
  - public method generics follow Nuxt `AsyncData` typing more closely
26
28
  - reactive `key`, `baseURL`, `params`, `query`, `headers`, `body`, and `cache` values are resolved before each request
27
29
  - generated keys are derived with Nuxt's `hashKey` (the same digest `useFetch` uses) and include both `params` and `query`, which avoids stale client reuse when only one side changes
28
- - same-key client compatibility requests share one async-data bucket, so `dedupe: 'cancel'` can abort the previous pending request
29
- - the client compatibility path mirrors Nuxt 4 async-data behavior: `pending` follows the `pendingWhenIdle` config, `refreshNuxtData()` (the `app:data:refresh` hook) re-runs fallback requests, `getCachedData` is honored and successful data is written back to `nuxtApp.payload.data`
30
+ - same-key calls after mount share request state. Clearing or replacing a request prevents its result from overwriting that state, including while an asynchronous `transform` is running
31
+ - after hydration, the default cache uses prerendered data for the initial load. Changes to watched sources fetch fresh data
32
+ - the client compatibility path mirrors Nuxt 4 async-data behavior: `pending` follows the `pendingWhenIdle` config, `refreshNuxtData()` (the `app:data:refresh` hook) re-runs fallback requests, `getCachedData` is honored and successful data is written back to `nuxtApp.payload.data` unless `serialize: false` is set
30
33
  - the client compatibility path honors Nuxt 4.5's `enabled` option (a reactive `enabled` turning `false` cancels the in-flight request) and cancels an in-flight request when its owning scope is disposed
34
+ - on Nuxt 4.6, the client compatibility path also honors async-data `middleware` (first entry outermost, before `transform`/`pick`) and `serialize: false`, including cached results
31
35
  - timeouts and external abort signals are merged into one request signal (via `AbortSignal.timeout`/`AbortSignal.any` semantics), key watchers are only created for reactive keys, and a key change re-runs the request when `immediate`, prior data, or an in-flight request is present
32
36
  - Vitest runtime tests and TypeScript type tests cover the wrapper behavior
33
37
 
@@ -41,7 +45,7 @@ The current implementation is maintained around these guarantees:
41
45
  - param or query preprocessing through `handler`
42
46
  - one request API that still works after mount on the client
43
47
 
44
- If all you need is a typed composable with shared defaults, prefer Nuxt's official factories:
48
+ If all you need is a typed composable with shared defaults, prefer Nuxt's official factories. Nuxt 4.6 also adds `defineUseFetchAddon` and `defineUseAsyncDataAddon` for reusable options, middleware, and return-value extensions:
45
49
 
46
50
  ```ts
47
51
  export const useAPI = createUseFetch({
@@ -60,7 +64,7 @@ export const useCachedData = createUseAsyncData({
60
64
  - After hydration on the client, calls made outside component setup (event handlers, lifecycle hooks such as `onMounted`, watchers) fall back to a compatibility mode. This is the same condition under which Nuxt warns "Component is already mounted".
61
65
  - The compatibility mode still exposes `data`, `error`, `status`, `pending`, `refresh`, `execute`, and `clear`.
62
66
  - The compatibility mode is not a full SSR payload or cache replacement.
63
- - Calls that intentionally share the same `key` should keep `handler`, `deep`, `transform`, `pick`, `getCachedData`, and `default` consistent, matching Nuxt's keyed async-data rules.
67
+ - Calls that intentionally share the same `key` should keep `handler`, `deep`, `transform`, `pick`, `getCachedData`, and `default` consistent, matching Nuxt's keyed async-data rules. On Nuxt 4.6, keep `middleware` and `serialize` consistent too.
64
68
 
65
69
  ## Installation
66
70
 
@@ -165,7 +169,7 @@ The remaining helper names follow the same rule: `getPageList` is the plain non-
165
169
 
166
170
  ## Upgrading From 4.4.x
167
171
 
168
- - Nuxt `>= 4.5.0` is required.
172
+ - Nuxt `^4.5.0` is required.
169
173
  - Calls made in `setup` during client-side navigation now go through `useAsyncData`, so `lazy: true` no longer blocks navigation and `server`/`enabled` follow Nuxt's rules. Calls from event handlers, `onMounted`, or watchers still use the compatibility mode.
170
174
  - Errors thrown by `useAsyncData` are no longer swallowed and turned into a fallback.
171
175
  - Requests are sent with `query` only; `params` is merged into it. Interceptors still see `options.params`, which ofetch mirrors from `query`.
@@ -227,7 +231,7 @@ Available methods:
227
231
  - `ajax.post(url, config?, asyncDataOptions?)`
228
232
  - `ajax.request(url, { method, ...config }, asyncDataOptions?)`
229
233
 
230
- The return value follows Nuxt's `AsyncData<...>` shape and can use the same `default`, `pick`, `transform`, `watch`, `dedupe`, `timeout`, and `enabled` options you already know from `useAsyncData`.
234
+ The return value follows Nuxt's `AsyncData<...>` shape and can use the same `default`, `pick`, `transform`, `watch`, `dedupe`, `timeout`, and `enabled` options you already know from `useAsyncData`. Nuxt 4.6 additionally provides `serialize` and `middleware`.
231
235
 
232
236
  `showLogs` defaults to `true` in development and prints each client request with `console.info` (real problems such as an unserializable body still use `console.warn`). Set `showLogs: false` to silence it.
233
237
 
@@ -256,6 +260,9 @@ The return value follows Nuxt's `AsyncData<...>` shape and can use the same `def
256
260
 
257
261
  ## References
258
262
 
263
+ - https://github.com/nuxt/nuxt/releases/tag/v4.6.0
264
+ - https://github.com/nuxt/nuxt/releases/tag/v4.7.0
265
+ - https://nuxt.com/docs/4.x/api/utils/define-use-fetch-addon
259
266
  - https://nuxt.com/docs/4.x/api/composables/create-use-async-data
260
267
  - https://nuxt.com/docs/4.x/api/composables/create-use-fetch
261
268
  - https://nuxt.com/docs/4.x/api/composables/use-async-data
package/dist/module.json CHANGED
@@ -1,9 +1,12 @@
1
1
  {
2
2
  "name": "nuxt-custom-fetch",
3
3
  "configKey": "customFetch",
4
- "version": ">=4.5.0",
4
+ "compatibility": {
5
+ "nuxt": "^4.5.0"
6
+ },
7
+ "version": "4.6.1",
5
8
  "builder": {
6
- "@nuxt/module-builder": "1.0.2",
9
+ "@nuxt/module-builder": "1.0.4",
7
10
  "unbuild": "unknown"
8
11
  }
9
12
  }
package/dist/module.mjs CHANGED
@@ -1,11 +1,13 @@
1
1
  import { fileURLToPath } from 'node:url';
2
- import { defineNuxtModule, createResolver, addImports } from '@nuxt/kit';
2
+ import { defineNuxtModule, createResolver, addImports } from 'nuxt/kit';
3
3
 
4
4
  const nuxtCustomFetch = defineNuxtModule({
5
5
  meta: {
6
6
  name: "nuxt-custom-fetch",
7
7
  configKey: "customFetch",
8
- version: ">=4.5.0"
8
+ compatibility: {
9
+ nuxt: "^4.5.0"
10
+ }
9
11
  },
10
12
  defaults: {},
11
13
  setup(options, nuxt) {
@@ -6,6 +6,10 @@ import { generateOptionSegments, Noop, pick, resolveReactiveValue } from "./util
6
6
  const _cachedController = /* @__PURE__ */ new Map();
7
7
  const _cachedClientAsyncData = /* @__PURE__ */ new Map();
8
8
  const MAX_UNSCOPED_CLIENT_ASYNC_DATA_ENTRIES = 50;
9
+ const DISABLED_ABORT_MESSAGE = "AsyncData request cancelled by `enabled: false`";
10
+ function readOwnEntry(entries, key) {
11
+ return entries && Object.hasOwn(entries, key) ? entries[key] : void 0;
12
+ }
9
13
  function createAbortController() {
10
14
  return typeof AbortController !== "undefined" ? new AbortController() : void 0;
11
15
  }
@@ -17,7 +21,9 @@ function linkAbortSignal(signal, controller) {
17
21
  controller.abort(signal.reason);
18
22
  return;
19
23
  }
20
- signal.addEventListener("abort", () => controller.abort(signal.reason), { once: true });
24
+ const onAbort = () => controller.abort(signal.reason);
25
+ signal.addEventListener("abort", onAbort, { once: true });
26
+ return () => signal.removeEventListener("abort", onAbort);
21
27
  }
22
28
  function createMergedSignal(signals, timeout) {
23
29
  const controller = createAbortController();
@@ -28,6 +34,9 @@ function createMergedSignal(signals, timeout) {
28
34
  if (typeof timeout === "number" && timeout >= 0 && typeof AbortSignal !== "undefined" && typeof AbortSignal.timeout === "function") {
29
35
  sources.push(AbortSignal.timeout(timeout));
30
36
  }
37
+ if (typeof AbortSignal !== "undefined" && typeof AbortSignal.any === "function") {
38
+ return AbortSignal.any(sources);
39
+ }
31
40
  for (const signal of sources) {
32
41
  linkAbortSignal(signal, controller);
33
42
  }
@@ -259,6 +268,7 @@ export class CustomFetch {
259
268
  };
260
269
  const nuxtApp = useNuxtApp();
261
270
  const createClientAsyncDataFallback = () => {
271
+ const fallbackOptions = options;
262
272
  const _ref = options.deep ? ref : shallowRef;
263
273
  const usePendingRef = pendingWhenIdle;
264
274
  const getDefaultValue = () => {
@@ -272,16 +282,26 @@ export class CustomFetch {
272
282
  return options.getCachedData(key.value, nuxtApp, { cause });
273
283
  }
274
284
  if (nuxtApp.isHydrating) {
275
- return nuxtApp.payload?.data?.[key.value];
285
+ return readOwnEntry(nuxtApp.payload?.data, key.value);
276
286
  }
277
- if (cause !== "refresh:manual" && cause !== "refresh:hook") {
278
- return nuxtApp.static?.data?.[key.value];
287
+ if (cause === "initial") {
288
+ return readOwnEntry(nuxtApp.static?.data, key.value);
279
289
  }
280
290
  return void 0;
281
291
  };
282
292
  const writePayloadData = (value) => {
283
- if (nuxtApp.payload?.data) {
284
- nuxtApp.payload.data[key.value] = value;
293
+ const payload = nuxtApp.payload?.data;
294
+ if (fallbackOptions.serialize !== false && payload) {
295
+ if (key.value === "__proto__" && !Object.hasOwn(payload, key.value)) {
296
+ Object.defineProperty(payload, key.value, {
297
+ configurable: true,
298
+ enumerable: true,
299
+ writable: true,
300
+ value
301
+ });
302
+ } else {
303
+ payload[key.value] = value;
304
+ }
285
305
  }
286
306
  };
287
307
  const isKeyReactive = isRef(resolvedConfig.key) || typeof resolvedConfig.key === "function";
@@ -302,6 +322,22 @@ export class CustomFetch {
302
322
  pendingRef.value = value;
303
323
  }
304
324
  };
325
+ const abortActiveRequest = (reason) => {
326
+ requestId++;
327
+ activeController?.abort(reason);
328
+ activeRequest = void 0;
329
+ activeController = void 0;
330
+ _cachedController.delete(key.value);
331
+ };
332
+ const cancelPendingRequest = (message) => {
333
+ if (activeRequest) {
334
+ abortActiveRequest(new DOMException(message, "AbortError"));
335
+ if (statusRef.value === "pending") {
336
+ statusRef.value = "idle";
337
+ }
338
+ setPending(false);
339
+ }
340
+ };
305
341
  const stopWatchers = () => {
306
342
  stopKeyWatch?.();
307
343
  stopKeyWatch = void 0;
@@ -319,8 +355,7 @@ export class CustomFetch {
319
355
  pending: pendingRef,
320
356
  clear: () => {
321
357
  stopWatchers();
322
- activeController?.abort();
323
- _cachedController.delete(key.value);
358
+ abortActiveRequest();
324
359
  if (_cachedClientAsyncData.get(key.value) === asyncData) {
325
360
  _cachedClientAsyncData.delete(key.value);
326
361
  }
@@ -337,48 +372,75 @@ export class CustomFetch {
337
372
  execute: async (executeOptions) => {
338
373
  const cause = executeOptions?.cause;
339
374
  const dedupe = executeOptions?.dedupe ?? options.dedupe ?? "cancel";
340
- if (activeRequest) {
341
- if (dedupe === "defer") {
342
- return activeRequest;
343
- }
344
- activeController?.abort();
375
+ if (activeRequest && dedupe === "defer") {
376
+ return activeRequest;
345
377
  }
346
378
  if (granularCachedData || cause === "initial" || nuxtApp.isHydrating) {
347
379
  const cachedData = resolveCachedData(cause);
348
380
  if (cachedData !== void 0) {
381
+ if (cause !== "initial" && activeRequest) {
382
+ abortActiveRequest(new DOMException("AsyncData request cancelled by cache hit", "AbortError"));
383
+ }
349
384
  writePayloadData(cachedData);
350
385
  hasData = true;
351
386
  asyncData.data.value = cachedData;
352
387
  asyncData.error.value = asyncDataDefaults.errorValue;
353
388
  asyncData.status.value = "success";
354
- setPending(false);
389
+ setPending(activeRequest !== void 0);
355
390
  return;
356
391
  }
357
392
  }
358
393
  if (toValue(options.enabled) === false) {
394
+ cancelPendingRequest(DISABLED_ABORT_MESSAGE);
359
395
  return;
360
396
  }
361
397
  const currentRequestId = ++requestId;
398
+ activeController?.abort();
362
399
  const controller = createAbortController();
363
400
  activeController = controller;
364
- linkAbortSignal(executeOptions?.signal, controller);
401
+ const removeExternalAbortListener = linkAbortSignal(executeOptions?.signal, controller);
365
402
  if (controller) {
366
403
  _cachedController.set(key.value, controller);
367
404
  }
368
405
  setPending(true);
369
406
  asyncData.status.value = "pending";
370
407
  asyncData.error.value = asyncDataDefaults.errorValue;
371
- activeRequest = executeRequest({
408
+ const signal = createMergedSignal([controller?.signal], executeOptions?.timeout ?? options.timeout);
409
+ let run = () => executeRequest({
372
410
  ...executeOptions,
373
- signal: controller?.signal
374
- }).then(async (result) => {
375
- if (currentRequestId !== requestId) {
411
+ signal
412
+ });
413
+ for (let i = (fallbackOptions.middleware?.length ?? 0) - 1; i >= 0; i--) {
414
+ const middleware = fallbackOptions.middleware[i];
415
+ const next = run;
416
+ run = () => Promise.resolve(middleware(next, { signal }));
417
+ }
418
+ let removeAbortListener;
419
+ const request = new Promise((resolve, reject) => {
420
+ const onAbort = () => reject(signal?.reason ?? new DOMException("Aborted", "AbortError"));
421
+ if (signal?.aborted) {
422
+ onAbort();
376
423
  return;
377
424
  }
378
- let data = result;
425
+ signal?.addEventListener("abort", onAbort, { once: true });
426
+ removeAbortListener = () => signal?.removeEventListener("abort", onAbort);
427
+ const result = run();
379
428
  if (options.transform) {
380
- data = await options.transform(result);
429
+ result.then((value) => {
430
+ if (currentRequestId !== requestId || signal?.aborted) {
431
+ return value;
432
+ }
433
+ return options.transform(value);
434
+ }).then(resolve, reject);
435
+ } else {
436
+ result.then(resolve, reject);
381
437
  }
438
+ });
439
+ activeRequest = request.then((result) => {
440
+ if (currentRequestId !== requestId || signal?.aborted) {
441
+ return;
442
+ }
443
+ const data = result;
382
444
  let finalData = data;
383
445
  if (options.pick) {
384
446
  finalData = pick(data, options.pick);
@@ -398,6 +460,8 @@ export class CustomFetch {
398
460
  asyncData.data.value = getDefaultValue();
399
461
  asyncData.status.value = "error";
400
462
  }).finally(() => {
463
+ removeAbortListener?.();
464
+ removeExternalAbortListener?.();
401
465
  if (currentRequestId !== requestId) {
402
466
  return;
403
467
  }
@@ -412,20 +476,6 @@ export class CustomFetch {
412
476
  await activeRequest;
413
477
  }
414
478
  };
415
- const cancelActiveRequest = (reason) => {
416
- if (!activeRequest) {
417
- return;
418
- }
419
- requestId++;
420
- activeController?.abort(new DOMException(reason, "AbortError"));
421
- activeRequest = void 0;
422
- activeController = void 0;
423
- _cachedController.delete(key.value);
424
- if (asyncData.status.value === "pending") {
425
- asyncData.status.value = "idle";
426
- }
427
- setPending(false);
428
- };
429
479
  _cachedClientAsyncData.set(key.value, asyncData);
430
480
  stopRefreshHook = nuxtApp.hook?.("app:data:refresh", async (keys) => {
431
481
  if (!keys || keys.includes(key.value)) {
@@ -469,7 +519,7 @@ export class CustomFetch {
469
519
  if (isRef(options.enabled) || typeof options.enabled === "function") {
470
520
  stopEnabledWatch = watch(() => toValue(options.enabled), (isEnabled) => {
471
521
  if (!isEnabled) {
472
- cancelActiveRequest("AsyncData request cancelled by `enabled: false`");
522
+ cancelPendingRequest(DISABLED_ABORT_MESSAGE);
473
523
  }
474
524
  });
475
525
  }
@@ -479,7 +529,7 @@ export class CustomFetch {
479
529
  if (hasScope) {
480
530
  onScopeDispose(() => {
481
531
  stopWatchers();
482
- cancelActiveRequest("AsyncData request cancelled by unmount");
532
+ cancelPendingRequest("AsyncData request cancelled by unmount");
483
533
  });
484
534
  }
485
535
  if (options.immediate === false) {
@@ -487,7 +537,7 @@ export class CustomFetch {
487
537
  }
488
538
  return asyncData.execute({ cause: "initial" }).then(() => asyncData);
489
539
  };
490
- const sharedAsyncData = nuxtApp._asyncData?.[key.value];
540
+ const sharedAsyncData = readOwnEntry(nuxtApp._asyncData, key.value);
491
541
  const cachedClientAsyncData = _cachedClientAsyncData.get(key.value);
492
542
  const instance = getCurrentInstance();
493
543
  if (import.meta.client && !nuxtApp.isHydrating && !nuxtApp._processingMiddleware && (!instance || instance.isMounted)) {
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "nuxt-custom-fetch",
3
3
  "type": "module",
4
- "version": "4.5.0",
4
+ "version": "4.6.1",
5
5
  "packageManager": "pnpm@11.7.0",
6
6
  "license": "MIT",
7
7
  "repository": {
@@ -41,20 +41,20 @@
41
41
  }
42
42
  },
43
43
  "peerDependencies": {
44
- "nuxt": ">=4.5.0",
44
+ "nuxt": "^4.5.0",
45
45
  "vue": "^3.5.30"
46
46
  },
47
47
  "dependencies": {
48
- "@vue/shared": "^3.5.30",
49
- "ohash": "^2.0.11"
48
+ "@vue/shared": "^3.5.46",
49
+ "ohash": "^2.0.12"
50
50
  },
51
51
  "devDependencies": {
52
52
  "@antfu/eslint-config": "^9.0.0",
53
53
  "@commitlint/cli": "^21.0.2",
54
54
  "@commitlint/config-conventional": "^21.0.2",
55
- "@nuxt/kit": "4.5.2",
56
- "@nuxt/module-builder": "^1.0.2",
57
- "@nuxt/schema": "4.5.2",
55
+ "@nuxt/kit": "4.7.0",
56
+ "@nuxt/module-builder": "^1.0.4",
57
+ "@nuxt/schema": "4.7.0",
58
58
  "@types/node": "^25.5.0",
59
59
  "@vitest/coverage-v8": "^4.1.9",
60
60
  "changelogen": "^0.6.2",
@@ -63,11 +63,11 @@
63
63
  "eslint": "^10.0.3",
64
64
  "husky": "^9.1.7",
65
65
  "nano-staged": "^1.0.2",
66
- "nitropack": "^2.13.1",
67
- "nuxt": "4.5.2",
66
+ "nitropack": "^2.14.0",
67
+ "nuxt": "4.7.0",
68
68
  "typescript": "6.0.3",
69
69
  "vitest": "^4.1.9",
70
- "vue": "^3.5.30"
70
+ "vue": "^3.5.46"
71
71
  },
72
72
  "husky": {
73
73
  "hooks": {