84669 person learning
152542 person learning
20005 person learning
5487 person learning
7821 person learning
359900 person learning
3350 person learning
180660 person learning
48569 person learning
18603 person learning
40936 person learning
1549 person learning
1183 person learning
32909 person learning
How to set the baseUrl used in the global useFetch composable (probably nuxt.config.ts)?
How to avoid defining it in every useFetch?
You can definebaseURLinnuxt.config.js|tslike this:
baseURL
nuxt.config.js|ts
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 useuseMyFetchas a replacement foruseFetch- but set the baseURL :-)
useMyFetch
useFetch
You can define
baseURL
innuxt.config.js|ts
like this:(or use fixed values or just environment variables - depending on your preference)
and add this composable:
If you want type safety, you can achieve it like this:
You can then use
useMyFetch
as a replacement foruseFetch
- but set the baseURL :-)