How to set the baseUrl used in the global useFetch composable (probably nuxt.config.ts)?
How to avoid defining it in every useFetch?
P粉6383439952023-10-23 15:33:58
You can define baseURL
in 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 fixed values or just environment variables - depending on your preference)
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 a replacement for useFetch
- but set the baseURL :-)