Skip to content
back to blog
developmentDecember 3, 2026 · 4 min read

Nuxt useFetch Addons: Stop Forking the Composable for Polling and Auth

Nuxt 4.6 addons let createUseFetch gain typed options like pollEvery or auth, plus middleware and extra return values, without wrapping useFetch.

Dan Holloran
Dan Holloran
Senior Fullstack Developer
Nuxt useFetch Addons: Stop Forking the Composable for Polling and Auth

Every Nuxt app I've worked on eventually grows a useApi wrapper. It starts innocently: a base URL and an auth header. Then someone needs polling on the dashboard, so a poll option gets bolted on. Then retries. Then "refresh when the tab comes back into focus." Six months later the wrapper is 200 lines, its types are a pile of Omit<> and Partial<>, and nobody wants to touch it because every page in the app goes through it.

Nuxt 4.4 gave us createUseFetch and createUseAsyncData, which fixed the first half of that story: you can stamp out a typed useFetch with your own defaults instead of wrapping it. Nuxt 4.6 fixes the second half with addons. An addon is a small, reusable unit of behavior you hand to the factory. It can declare new call-site options (fully typed), hook into the request, wrap the handler in middleware, and add properties to what the composable returns. Your custom composable becomes a list of features instead of a pile of conditionals.

The shape of an addon ​

You define one with defineUseFetchAddon (or defineUseAsyncDataAddon for the async-data flavor) and pass it in the addons array. The setup function runs on every call with the merged options: factory defaults plus whatever the caller passed. Code in setup runs before the underlying useAsyncData call. If setup returns a function, that function runs after, receives the async data instance, and anything it returns is merged into the composable's return value.

Here's an auth addon that adds an auth option, defaulting to on:

ts
// app/composables/useApi.ts
const auth = defineUseFetchAddon({
  setup: (
    options: UseFetchAddonOptions<{ auth?: MaybeRefOrGetter<boolean> }>,
  ) => {
    const { token } = useTokenStore();
    options.auth ??= true;

    options.onRequest.push(({ options: fetchOptions }) => {
      if (!toValue(options.auth)) return;
      fetchOptions.headers.set("Authorization", `Bearer ${token.value}`);
    });
  },
});

export const useApi = createUseFetch({ baseURL: "/api", addons: [auth] });

The type annotation on the options parameter is doing the heavy lifting. UseFetchAddonOptions<{ auth?: ... }> tells Nuxt that useApi now accepts an auth key, so callers get autocomplete and a type error if they pass auth: 'yes':

vue
<script setup lang="ts">
const { data } = await useApi("/public/changelog", { auth: false });
</script>

Note that onRequest is an array here. Nuxt normalizes middleware, onRequest, onRequestError, onResponse, and onResponseError to arrays before addons see them, so you push your interceptor instead of overwriting the caller's. That one detail removes a whole class of "my wrapper silently dropped your onResponse" bugs.

Adding behavior and return values ​

The after-function is where reactive features live. This polling addon adds a pollEvery option and stops polling while the tab is hidden, because hammering an API from a background tab helps nobody:

ts
const polling = defineUseFetchAddon({
  setup: (options: UseFetchAddonOptions<{ pollEvery?: number }>) => {
    if (import.meta.server || !options.pollEvery) return;

    return (asyncData) => {
      const lastPolledAt = ref<Date>();
      const id = setInterval(() => {
        if (document.visibilityState !== "visible") return;
        asyncData.refresh();
        lastPolledAt.value = new Date();
      }, options.pollEvery);

      onScopeDispose(() => clearInterval(id));
      return { lastPolledAt: readonly(lastPolledAt) };
    };
  },
});

export const useApi = createUseFetch({
  baseURL: "/api",
  addons: [auth, polling],
});

The import.meta.server guard matters: intervals on the server would leak across requests, so the addon only wires up in the browser. And because the after-function returned { lastPolledAt }, it shows up typed on the result:

vue
<script setup lang="ts">
const { data: jobs, lastPolledAt } = await useApi("/jobs", {
  pollEvery: 15_000,
});
</script>

For wrapping the request itself, use options.middleware. Middleware gets a next() function, and the first addon in the array is the outermost wrapper. The docs' example enforces a minimum duration so a loading spinner doesn't flash for 40ms:

ts
const minDuration = defineUseFetchAddon({
  setup: (options: UseFetchAddonOptions<{ minDuration?: number }>) => {
    options.middleware.push(async (next) => {
      const [result] = await Promise.all([
        next(),
        new Promise((resolve) =>
          setTimeout(resolve, toValue(options.minDuration) ?? 300),
        ),
      ]);
      return result;
    });
  },
});

The cache-key gotcha ​

Here's the part that will bite you if you skim. Custom options are not part of the auto-generated cache key. If an option changes the response, two calls that differ only by that option will share one cached entry. A tenant or scope option is the classic case. Fix it with a key resolver:

ts
const scoped = defineUseFetchAddon({
  setup: (options: UseFetchAddonOptions<{ scope?: string }>) => {
    options.scope ??= "default";
    options.onRequest.push(({ options: fetchOptions }) => {
      fetchOptions.headers.set("X-Scope", toValue(options.scope)!);
    });
  },
  key: (options) => toValue(options.scope),
});

Declare setup before key. TypeScript infers the custom option types from setup's parameter annotation, and if key comes first it gets checked against empty options.

A few other rules worth knowing: addons run in array order, listing the same addon object twice only runs it once, and custom options also get passed through to $fetch, which ignores keys it doesn't recognize. That last one means don't name a custom option after a real $fetch option like timeout or retry unless you actually mean it.

When to reach for it ​

Addons are worth it once you have two or more cross-cutting behaviors, or one you want to share across several custom composables (an admin API and a public API that both poll, for example). For a single base URL and header, a plain createUseFetch with defaults is still simpler. And if your polling, caching, and retry needs are getting serious, it's worth asking whether a dedicated data layer like Pinia Colada or TanStack Query fits better than growing your own.

You'll need Nuxt 4.6 or newer. The defineUseFetchAddon reference covers the advanced escape hatches, like wrapping then and catch on the awaitable result, and the Nuxt 4.6 release post has the background. Start by deleting one if from your wrapper and turning it into an addon. The rest tends to follow.

~/subscribe
# new posts on code, craft & travel — no noise, no schedule