How to custom baseURL of fetching api as our own?
Hello everyone, can anyone help me about how we can fetching the api without put baseURL everytime we want to get the data. So I don't want to make like this
2 Replies
Hi @Adnan Erlansyah. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
----------------------
To customize the baseURL for your API fetching without specifying it every time, you can create a custom fetch wrapper in Nuxt. Here's how you can do it:
1. First, create a Nuxt plugin to set up a custom $fetch instance:
2. Then, create a custom composable to use this $api instance:
3. Now you can use this custom
useAPI
composable in your components without specifying the baseURL each time:
This approach allows you to set the baseURL once and reuse it across your application. The baseURL is set using the runtimeConfig
in your nuxt.config.ts
file, which can be overridden by environment variables.
Source: Nuxt Docs - Custom useFetch (https://nuxt.com/docs/guide/recipes/custom-usefetch#custom-fetch)
Remember to set up your runtimeConfig
in nuxt.config.ts
:
Source: Nuxt Docs - Runtime Config (https://nuxt.com/docs/guide/going-further/runtime-config#exposing)
This setup allows you to have a clean and reusable way to fetch data from your API without repeating the baseURL in every request.
----------------------
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
----------------------<@1079709612078534676> Kapa.ai is still learning and improving, please let me know how I did by reacting below.