How do I set the baseUrl that is used in the useFetch composable globally (maybe nuxt.config.ts)?
How can I avoid defining it in every useFetch?
You can define the baseURL
in your nuxt.config.js|ts
like this:
import { defineNuxtConfig } from 'nuxt'
export default defineNuxtConfig({
// ...
runtimeConfig: {
public: {
baseURL: process.env.BASE_URL || 'https://api.example.com/',
},
},
// ...
(or use a fixed value or only the environment variable - as you like)
And add this composable:
// /composables/useMyFetch.js
export const useMyFetch = (request, opts) => {
const config = useRuntimeConfig()
return useFetch(request, { baseURL: config.public.baseURL, ...opts })
}
If you want type safety, you can achieve it like this:
// /composables/useMyFetch.ts
export const useMyFetch: typeof useFetch = (request, opts?) => {
const config = useRuntimeConfig()
return useFetch(request, { baseURL: config.public.baseURL, ...opts })
}
You can then use useMyFetch
as replacement for useFetch
- but with baseURL being set :-)
The following composable could be set
/composables/useJsonP.ts
export const useJsonP = async (path) => {
return await useFetch(() => `https://jsonplaceholder.typicode.com/${path}`)
}
And you could call this in your view
<script setup>
const jsonP = await useJsonP('todos/1')
</script>
<template>
<div>
<pre>{{ jsonP.data }}</pre>
</div>
</template>
That way, no need to define it somewhere and hack somehow the configuration. You do have a simple way of defining reusable pieces of code, that are directly imported into your components/views thanks to the DX of Nuxt.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With