Global $fetch hooks
Is it possible to globally define hooks for
onRequest
and onResponseError
(apart from having to create a custom useFetch
and use that everywhere)?2 Replies
Hi @Septatrix. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
----------------------
Yes, it is possible to globally define hooks for
onRequest
and onResponseError
in Nuxt without creating a custom useFetch
. You can achieve this by creating a custom $fetch
instance with global interceptors using a Nuxt plugin. Here's how you can do it:
1. Create a Nuxt plugin file, for example, plugins/api.ts
:
2. This plugin creates a custom $fetch
instance with global interceptors and exposes it as $api
through useNuxtApp()
.
3. You can then use this custom $api
in your components or pages:
This approach allows you to define global hooks for all API calls made through $api
without having to create a custom useFetch
composable.
Source: Custom $fetch
in Nuxt (https://nuxt.com/docs/guide/recipes/custom-usefetch#custom-fetch)
It's worth noting that while this method provides a way to set up global interceptors, it's not directly modifying the global $fetch
or useFetch
. Instead, it creates a new instance with the desired behavior. This approach is recommended because the core $fetch
utility is intentionally not globally configurable to maintain consistent behavior throughout the application.
Source: Custom useFetch in Nuxt (https://nuxt.com/docs/guide/recipes/custom-usefetch)
For more detailed information and examples, you can refer to the video tutorial: Custom $fetch and Repository Pattern in Nuxt 3 (https://www.youtube.com/watch?v=jXH8Tr-exhI).
----------------------
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
----------------------<@525348219828568076> Kapa.ai is still learning and improving, please let me know how I did by reacting below.