I’m migrating a Nuxt 2 application to Nuxt 3 (Vue2 to Vue3 as well) and I used to use Axios library in my old application but now Vue 3 has its own internal fetch to make HTTP requests so Axios library for Nuxt 3 is not supported anymore. I followed the documentation on how to create a custom fetch function and it’s working fine but I want to add a wrapper around it to make it work in a similar way as it used to with Axios. Currently I’m making my requests like this:
const resp = await useAPI(`/user/${url}`, {method: "POST", body: data})
I would like to call my composable like this:
const resp = await useAPI.post(`/user/${url}`, data, {/*any additional header*/})
I can’t grasp my head around how to wrap the plugin for it to work this way, here’s my customFetch plugin and my composable
customFetch plugin
export default defineNuxtPlugin((nuxtApp) => {
const token = useCookie('token')
const api = $fetch.create({
baseURL: "http://localhost:3012",
onRequest({ request, options, error }) {
if (token.value) {
const headers = options.headers ||= {}
if (Array.isArray(headers)) {
headers.push(['Authorization', `Bearer ${token.value}`])
} else if (headers instanceof Headers) {
headers.set('Authorization', `Bearer ${token.value}`)
} else {
headers.Authorization = `Bearer ${token.value}`
}
}
},
async onResponseError({ response }) {
if (response.status === 401) {
await nuxtApp.runWithContext(() => navigateTo('/login'))
}
}
})
// Expose to useNuxtApp().$api
return {
provide: {
api
}
}
})
useAPI composable
import type { UseFetchOptions } from 'nuxt/app'
export function useAPI<T>(
url: string | (() => string),
options: UseFetchOptions<T> = {},
) {
return useFetch(url, {
...options,
$fetch: useNuxtApp().$api as any
})
}