I want to be able to make an api request without adding the base url, like this
await useFetch('/products/shoes')
I have setup my .env and runtimeconfig
.env file
NUXT_PUBLIC_API_BASE='https://myonlinestore.herokuapp.com/api/v1'
NUXT_APP_API_PROD_URL='https://api.myonlinestore.ng/api/v1'
and my nuxt.config.ts file looks like this
export default defineNuxtConfig({
devtools: { enabled: true },
css: ['@/assets/css/global.css'],
modules: [
'@nuxt/ui',
'@pinia/nuxt',
'@pinia-plugin-persistedstate/nuxt',
'dayjs-nuxt',
],
runtimeConfig: {
public: {
apiBase: process.env.NUXT_PUBLIC_API_BASE
}
}
});
But from the docs https://nuxt.com/docs/guide/going-further/runtime-config , it says you can access the runtimeconfig variables like this
<script setup lang="ts">
const config = useRuntimeConfig()
console.log('Runtime config:', config)
if (process.server) {
console.log('API secret:', config.apiSecret)
}
</script>
So to make a call, I did this
<script setup>
const route = useRoute();
const config = useRuntimeConfig()
const fetchProduct = async () => {
const {pending, data: response} = await useFetch(
`${config.public.apiBase}/products/shoes/${route.params}`)
}
</script>
But this means I have to do this on all pages before making a call. How can i do my setup so that i can make a request like this on all pages.
await useFetch('/products/shoes')
Your help is absolutely appreciated. Thanks.
Also, on the docs, it says
When adding apiBase to the runtimeConfig.public, Nuxt adds it to each page payload. We can universally access apiBase in both server and browser.
Does this mean that nuxt defaultly offers what i am trying to achieve?