Skip to content

Migration ​

v5.0.0 ​

The module refuses to start on an option v5 removed, and its error names each one along with what replaces it. Run nuxt prepare first to collect that list, then work through the sections below.

Code You Have to Change ​

Nuxt 4.4 Is Required ​

The module now requires Nuxt 4.4 or later.

openapi-typescript Is No Longer Needed ​

The types are generated by APIful, which the module depends on. Uninstall openapi-typescript unless something else in your app uses it, and drop openAPITS from the module options and from every endpoint – the generator takes no options:

ts
export default defineNuxtConfig({
  apiParty: {
    openAPITS: { exportType: true }, 
    endpoints: {
      petStore: {
        url: 'https://petstore3.swagger.io/api/v3',
        schema: './schemas/petStore.yaml',
        openAPITS: { rootTypes: true } 
      }
    }
  }
})

#nuxt-api-party/{endpointId} exports paths and components only. An option such as rootTypes that added an alias per schema object has no replacement; alias the schema objects you use yourself:

ts
import type { components } from '#nuxt-api-party/petStore'

export type Pet = components['schemas']['Pet']

The generated PetStoreModel<'Pet'> resolves to the same type. The operations interface is gone, since operations are inlined into paths – read an operation through PetStore<'/pet/{petId}', 'get'> instead.

An endpoint's schema takes an async function that resolves to the document again, so a schema resolved in the api-party:extend hook can move back into the option.

server.proxyMode and server.basePath Are Gone ​

The server option is removed. There is one server proxy now, serving <nitro.apiBaseURL>/__api_party/{endpointId}/{path} – /api/__api_party/{endpointId}/{path} by default – and forwarding each request under its own method, with its query, headers and body as they are:

ts
export default defineNuxtConfig({
  apiParty: {
    server: { 
      basePath: 'my-proxy', 
      proxyMode: 'passthrough'
    }, 
    endpoints: {}
  }
})

Unlike 'passthrough' mode, the proxy adds the endpoint's token, headers and query, so a request hook that attached them only for the passthrough proxy can go.

Rules of a CDN, a WAF or a rate limiter that matched the old route need the new path: a GET request is now a GET /api/__api_party/{endpointId}/{path}, not a POST /api/__api_party/{endpointId}. The /proxy/ segment of the passthrough route is gone as well: /api/__api_party/{endpointId}/proxy/{path} is now /api/__api_party/{endpointId}/{path}.

Code that built the POST envelope by hand sends a normal request to the route instead:

ts
await $fetch('/api/__api_party/auth', { 
  method: 'POST', 
  body: { path: 'login', method: 'POST', body: credentials } 
}) 
await $fetch('/api/__api_party/auth/login', { 
  method: 'POST', 
  body: credentials 
}) 

Better still, call $auth('login', { method: 'POST', body: credentials }).

cookies Is Now forwardCredentials ​

The endpoint option is renamed, and it now covers the Authorization header and the API's Set-Cookie as well as the cookie:

ts
export default defineNuxtConfig({
  apiParty: {
    endpoints: {
      myApi: {
        url: process.env.MY_API_BASE_URL!,
        cookies: true, 
        forwardCredentials: true
      }
    }
  }
})

Without forwardCredentials, the server proxy withholds the visitor's cookie and Authorization header from the API and keeps the API's Set-Cookie from the browser. With it, the API receives every cookie the browser sends to your app, your app's own session cookie included, and every cookie the API sets reaches the browser. See Credential Forwarding.

For an endpoint with forwardCredentials, the proxy now answers a cross-site request with 403. Call the proxy from your own site only – see Cross-Site Requests.

A Per-Visitor Authorization Header Needs forwardCredentials

An Authorization header set in a call's headers, an interceptor or a Nuxt hook used to travel to the API inside the POST envelope. It now reaches the proxy as a request header, which the proxy drops unless the endpoint sets forwardCredentials – the API answers 401. Set forwardCredentials: true on such an endpoint, or attach the header in a Nitro hook.

ts
// Sends the visitor's token only with `forwardCredentials: true` on `myApi`
await $myApi('me', {
  headers: { Authorization: `Bearer ${session.value.token}` }
})

The client Option Moved to the Endpoint ​

The module option client and the call option client are removed. An endpoint sets client: true to send every request straight to the API, from the browser and during SSR:

ts
export default defineNuxtConfig({
  apiParty: {
    client: 'always', 
    endpoints: {
      publicApi: {
        url: 'https://api.example.com',
        client: true
      }
    }
  }
})

There is no 'allow' any more. Where some calls went through the proxy and others opted out with client: true, configure the API twice, as two endpoints, one of them with client: true. Only client endpoints are published to the public runtime config now. See Client Endpoints.

An endpoint that sets client: true together with forwardCredentials or allowedRoutes fails the build, since neither applies without the proxy.

With ssr: false, an endpoint still defaults to a client endpoint – unless it sets forwardCredentials or allowedRoutes, which keep it on the server proxy. Drop both options from the endpoints of an app that is served statically, with no server to proxy through.

payloadCache and key on $myApi Are Gone ​

$myApi is a plain fetch now and stores nothing in the Nuxt payload. Wrap it in useAsyncData where its response should reach the browser through the payload:

ts
const data = await $myApi('posts', { key: 'posts', payloadCache: true }) 
const { data } = await useAsyncData('posts', () => $myApi('posts')) 

useMyApiData drops its payloadCache option for Nuxt's getCachedData. To answer a repeated request from the payload, as payloadCache did:

ts
const { data } = await useMyApiData('posts', {
  payloadCache: true, 
  getCachedData: (key, nuxtApp, { cause }) =>
    cause === 'initial'
      ? nuxtApp.payload.data[key] 
      : undefined
})

Nuxt calls getCachedData on refresh(), refreshNuxtData() and a change of a watch source as well, and checking cause sends those to the API, as before. payloadCache: false simply goes, since Nuxt's default doesn't cache past hydration. The module option payloadCache is removed. See Caching Strategies.

$myApi in Component Setup Fetches Twice ​

An awaited $myApi call in a component's setup used to hand its response to the browser through the payload. Now it runs during SSR and once more while the page hydrates, and no type error points there. In development, the module warns in the console when it happens. Wrap the call:

ts
const posts = await $myApi('posts') 
const { data: posts } = await useAsyncData('posts', () => $myApi('posts')) 

Or use useMyApiData('posts').

The Defaults Plugin Is Gone ​

A plugin that provided apiParty.defaults no longer has an effect, and the ModulePlugin, ModuleInjections and FetchOptionsDefaults types are gone. Set the defaults in an api-party:request hook instead. The hook runs before every attempt, a retry included, so assign with ??= – a plain assignment to retry resets the count each time, and a failing request retries without end:

ts
export default defineNuxtPlugin(() => { 
  return { 
    provide: { 
      apiParty: { 
        defaults: { retry: 2 }, 
        endpoints: { 
          jsonPlaceholder: { 
            defaults: { timeout: 5000 } 
          } 
        } 
      } 
    } 
  } 
}) satisfies ModulePlugin
export default defineNuxtPlugin((nuxtApp) => { 
  nuxtApp.hook('api-party:request', (ctx, endpointId) => { 
    ctx.options.retry ??= 2
    if (endpointId === 'jsonPlaceholder') 
      ctx.options.timeout ??= 5000
  }) 
}) 

A timeout set in the hook reaches neither useMyApiData nor a request through the server proxy during SSR. Static headers and query parameters belong in the endpoint's headers and query. Nuxt's experimental.defaults.useFetch sets retry and retryDelay for useMyApiData as well.

The Dynamic Backend URL Is Gone ​

The allowedUrls endpoint option is removed, and the proxy no longer reads a {endpointId}-Endpoint-Url header – it forwards it to the API like any other. Configure one endpoint per API URL and pick the composable at the call site:

ts
export default defineNuxtConfig({
  apiParty: {
    endpoints: {
      tenant: { 
        url: 'https://a.example.com', 
        allowedUrls: ['https://b.example.com'] 
      }, 
      tenantA: { url: 'https://a.example.com' }, 
      tenantB: { url: 'https://b.example.com' } 
    }
  }
})

Hooks Receive the Endpoint ID ​

The endpoint-specific hooks api-party:request:{endpointId} and api-party:response:{endpointId} are removed. The generic hooks receive the endpoint ID instead – as the second argument of the Nuxt hooks and the third of the Nitro hooks:

ts
nitroApp.hooks.hook('api-party:request:myApi', async (ctx, event) => {
  ctx.options.headers.set('Authorization', `Bearer ${await getUserToken(event)}`)
})
ts
nitroApp.hooks.hook('api-party:request', async (ctx, event, endpointId) => {
  if (endpointId !== 'myApi' || !event)
    return
  ctx.options.headers.set('Authorization', `Bearer ${await getUserToken(event)}`)
})

The $fetch Option Is Gone ​

A call no longer takes a $fetch of its own. Move what the custom fetch did into an interceptor or a hook.

Endpoint headers Take a Record of Strings ​

An endpoint's headers is typed Record<string, string> instead of HeadersInit, since the runtime config has to serialize it. A Headers instance or an array of pairs becomes a plain object:

ts
export default defineNuxtConfig({
  apiParty: {
    endpoints: {
      myApi: {
        url: process.env.MY_API_BASE_URL!,
        headers: new Headers({ 'X-Tenant': 'a' }), 
        headers: { 'X-Tenant': 'a' } 
      }
    }
  }
})

A call's headers option still accepts every HeadersInit.

useMyApiData Is Typed on Nuxt's useFetch ​

useMyApiData is built on Nuxt's useFetch now and takes its options and generic parameters: ResT, ErrorT, DataT, PickKeys and DefaultT. A single type argument keeps working, but transform, pick and default now type data, and error is NuxtError<ErrorT> | undefined. A wrapper that spelled out the old return type fails to compile:

ts
import type { AsyncData, NuxtError } from '#app'
import type { UseApiDataOptions } from '#nuxt-api-party'

export function useCms<T>(path: string, opts?: UseApiDataOptions<T>): AsyncData<T | undefined, NuxtError> {
  return useCmsData<T>(path, opts)
}
ts
import type { AsyncData, NuxtError } from '#app'
import type { UseApiDataOptions } from '#nuxt-api-party'

export function useCms<T>(path: string, opts?: UseApiDataOptions<T>): AsyncData<T | undefined, NuxtError | undefined> {
  return useCmsData<T>(path, opts)
}

Leaving the return type to inference works as well.

The FilterMethods type export is gone. A wrapper constrains its methods to the path item instead:

ts
import type { paths as PetStorePaths } from '#nuxt-api-party/petStore'

export function $petStoreCall<
  Path extends Extract<keyof PetStorePaths, string>,
  Methods extends FilterMethods<PetStorePaths[Path]>, 
  Methods extends PetStorePaths[Path], 
>(path: Path) {}

A call that passes options no longer type-checks where its path is a union of paths that declare different methods. Split it into one call per path.

Behavior That Changed ​

The Proxy Forwards Request Headers ​

The POST envelope forwarded only Origin, Referer and User-Agent of the browser's request. The proxy now forwards every request header except Host, the hop-by-hop headers, Accept-Encoding, Expect, and – without forwardCredentials – Cookie and Authorization. See Which Headers Travel.

A header the endpoint sets replaces one of the same name that a call sends through the proxy, where v4 sent both values.

Nitro Hooks See Streams and No Query Object ​

The proxy streams the API's response through, so in a Nitro api-party:response hook for a proxy request, ctx.response._data is a ReadableStream rather than the parsed body. A hook that read or replaced the body has to move that logic to the browser, into a Nuxt hook or an interceptor.

A Nitro api-party:request hook for a proxy request changed the same way: ctx.options.body is a ReadableStream on a POST, PUT, PATCH or DELETE request, and the query is already part of ctx.request, which leaves ctx.options.query undefined. A hook that set a property on it now throws, and the proxy answers 502. Assign the object instead:

ts
ctx.options.query.apiKey = apiKey 
ctx.options.query = { ...ctx.options.query, apiKey } 

Server Imports Fire the Nitro Hooks ​

A server import now fires the Nitro api-party:request and api-party:response hooks, with event set to undefined. A hook that assumed an event, or that should only act on proxy requests, checks event first.

A Rethrown Server Import Error Nests the API's Body ​

A Nitro route that rethrows the error of a server import with createError nests the API's body one level deeper, at error.data.data. To hand it on unchanged, answer with its status and body instead – see Rethrowing From Your Own Nitro Route.

Query Values No Longer Pass Through JSON ​

The POST envelope carried query as JSON, which turned a Date into its ISO string and a NaN into an empty value. The proxy now reads the query string of the request, so NaN arrives as NaN and a Date as a JSON-quoted string. Convert such values before the call:

ts
await $myApi('events', {
  query: {
    from: from.toISOString(),
    limit: Number.isNaN(limit)
      ? undefined
      : limit
  }
})

Redirects Are No Longer Followed ​

The proxy passes redirects back as the API sent them, and a server import resolves a 3xx response, instead of following them. Where the API redirects to a canonical path, call that path instead. See Redirects.

useMyApiData Neither Caches Nor Shares a Request by Default ​

v4 answered a repeated useMyApiData request from the payload unless payloadCache was false, and two call sites that asked for the same resource shared one request. Now every call site sends its own request, and a page fetches again when the visitor navigates back to it. Expect more requests where your app relied on either, and pass getCachedData where a call site may keep the response it has.

A Failed GET Request Is Sent Twice ​

A request through the proxy keeps its method, so ofetch retries it once, as it does for every $fetch: a request other than POST, PUT, PATCH and DELETE that fails with a network error or with 408, 409, 425, 429, 500, 502, 503 or 504. The POST envelope was never retried. Pass retry: 0 to keep the call from retrying. As in v4, the proxy itself sends such a request a second time when its connection to the API fails.

Browser Caching Works Through the Proxy ​

A GET request through the proxy stays a GET request, so the browser's HTTP cache serves it under the API's cache headers. Pass cache: 'no-store' where a call must always reach the API.

A Client Endpoint Gets No Visitor Credentials During SSR ​

During SSR, a request to a client endpoint leaves the server without the visitor's cookie or Authorization header.

v4.0.0 ​

Nuxt 4 Is Required ​

The module no longer supports Nuxt 3.

openapi-typescript v7 Is Required ​

The peer dependency used to accept ^5 || ^6 || ^7 and now accepts ^7 alone. Upgrade the package alongside the module and regenerate your schema types.

The experimental Namespace Is Gone ​

Its four flags moved out and two of them changed their default:

BeforeNowDefault
experimental.enablePrefixedProxy: trueserver.proxyMode: 'passthrough'Unchanged
experimental.disableClientPayloadCache: truepayloadCache: falseUnchanged
experimental.enableAutoKeyInjection: trueRemovedAlways on
experimental.enableSchemaFileWatcherRemovedAlways on in dev

Every useMyApiData call now gets its own async data state, keyed by its position in your source, the way Nuxt keys useFetch and useAsyncData – with no switch either way, as Nuxt has none. Two components asking for the same resource therefore no longer share a data ref, and no longer collide when their transform, pick or default options differ. They do still share the underlying request. Pass the same explicit key to put two call sites back on one instance.

refresh() Sends the Request Again ​

refresh(), clear() and a key change driven by a reactive option used to be answered with the response already cached for that request. Each of them now sends a new request. Expect more traffic where a page refreshes on an interval, and reach for getCachedData to decide when a call site may keep what it has.

cache Only Means the Browser Cache Now ​

cache used to accept a boolean alongside the RequestInit.cache values, and the boolean drove the payload cache. Payload caching now has its own option:

ts
const { data } = await useMyApiData('posts', {
  cache: false, 
  payloadCache: false
})

cache: true and cache: false are compile errors, so they surface on upgrade. One change is silent, though: a string value used to turn payload caching off as a side effect. cache: 'no-store' now only sets the browser cache mode, and the payload cache stays on unless you add payloadCache: false.

The Wrapped Proxy Reports 502 for an Unreachable API ​

An API that cannot be reached used to yield 503 Service Unavailable from the default proxy and 502 Bad Gateway from the passthrough one. Both report 502 now.

The Passthrough Proxy No Longer Forwards authorization ​

With server.proxyMode set to 'passthrough', a browser request's authorization header used to travel on to your API. It no longer does: the header carries the visitor's credentials for your app, not your app's credentials for the API.

A cookie still travels, but only for endpoints that set cookies: true. Note that the passthrough proxy forwards the request as it stands and does not add the endpoint's token, headers or query – only the default /api/__api_party/{endpointId} handler does. If you relied on the old behavior to pass a bearer token through, attach it in a request hook.

Endpoint Types Resolve Through the Client ​

Service<Path, Method> used to compute request, response and responses with its own type logic, which disagreed with what the composables returned. Both now resolve through the same helpers, so the type you extract is the type you get back.

Three consequences, all at type level:

  • A method the path doesn't declare is now a compile error. PetStore<'/pet', 'get'> fails where the schema declares only post and put; likewise PetStoreApiMethods<'/pet'> narrows from every HTTP verb to 'post' | 'put'.
  • An operation that declares no path or query parameters reports never, where the old logic answered undefined, and one that declares no request body reports undefined, where the old logic answered unknown.
  • A status code that carries no response body reports undefined in responses, in place of Record<string, never>. So does response for an operation whose success carries no body – PetStore<'/pet/{petId}', 'delete'>['response'] is now never.

See OpenAPI Type Helpers for what each property now reports.

schema No Longer Accepts a Function ​

An endpoint's schema takes a file path, a URL or the parsed schema object. Resolve a schema you have to build yourself in the api-party:extend hook instead, which runs at module initialization and can await:

ts
export default defineNuxtConfig({
  hooks: {
    'api-party:extend': async (options) => {
      options.endpoints!.myApi!.schema = await buildSchema()
    },
  },
})

Passing a function was deprecated in v2.1.0 and now throws.

Removed Deprecated Type Helpers ​

Response, RequestBody and RequestQuery are gone from #nuxt-api-party/{endpointId}. They were keyed by operation ID; the endpoint interface is keyed by path and method, which is what the composables take:

ts
import type { PetStore } from '#nuxt-api-party'
import type { Response } from '#nuxt-api-party/petStore'

type Pet = Response<'getPetById'> 
type Pet = PetStore<'/pet/{petId}', 'get'>['response'] 

RequestBody<'addPet'> becomes PetStore<'/pet', 'post'>['request'], and RequestQuery<'findPetsByStatus'> becomes PetStore<'/pet/findByStatus', 'get'>['query'].

v3.0.0 ​

Caching has been completely refactored in Nuxt API Party v3. If you are using caching, please read the caching documentation to understand the new caching system.

WARNING

Caching behavior is now controlled by the upstream endpoint. If your endpoint does not support caching, the responses will not be stored in the browser's cache. This is a breaking change from previous versions, where caching was done regardless.

The simplest way to ensure caching is enabled on the backend is to set the Cache-Control: max-age=3600 header on your API responses, which will cache the response for 1 hour.

See the MDN documentation on HTTP caching for more information on how to set up caching on your API.

  • Cached responses are no longer stored in the Nuxt payload data. Instead, they are stored in the browser's cache, which allows for better memory management and performance. This follows a change done in Nuxt 3.17.

  • Generated $myApi and useMyApiData composables now support the RequestInit.cache option. For convenience, you can pass true for 'default' caching, or false for 'no-store' caching.

  • $myApi composables now have caching enabled by default. To restore the old behavior, you can set the cache option to false or 'no-store' in the request options.

    ts
    const data = $petStore('/user/{username}', {
      cache: 'no-store', 
    })

v2.0.0 ​

TIP

Breaking changes are limited to using typed OpenAPI clients. If you don't require typed clients in your Nuxt application, you can skip this migration section.

With Nuxt API Party v2, the OpenAPI support has been refactored to conform to v7 of the openapi-typescript package. This change introduces a few breaking changes to the API Party OpenAPI client:

  • Dropped support for OpenAPI 2.0 (Swagger).
  • Previously, you could omit the leading slash in the API path. This is no longer possible. You must now include the leading slash in the path, just like in the OpenAPI specification.
  • The pathParams fetch option has been renamed to path to better align with the OpenAPI specification and allow for more flexibility in the future.
ts
const { data } = await usePetStoreData(
  'user/{username}', 
  '/user/{username}', 
  {
    pathParams: { username: 'user1' }, 
    path: { username: 'user1' }, 
  }
)

v1.0.0 ​

Following the release of Nuxt 3.9, type possibilities for errors returned by useAsyncData and useFetch have been significantly improved to make them more accurate in terms of what they actually contain. See the refactor PR for more information.

This change also affects the error handling for API Party composables. The error types have been updated to reflect the changes in Nuxt 3.9. As such, you may need to update your code to make use of the new type possibilities:

ts
import type { NuxtError } from '#app'

// The error is now typed as `NuxtError<unknown> | null`
const { data, error } = await useMyApiData('posts')

// For dollar API calls, the error has to be typed as `NuxtError`
try {
  await $myApi('posts')
}
catch (error) {
  console.error(error as NuxtError)
}

Released under the MIT License.