search

Home  >  Q&A  >  body text

In Nuxt 3 how to set the global API baseUrl used in useFetch

How to set the baseUrl used in the global useFetch composable (probably nuxt.config.ts)?

How to avoid defining it in every useFetch?

P粉757432491P粉757432491402 days ago1039

reply all(1)I'll reply

  • P粉638343995

    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 :-)

    reply
    0
  • Cancelreply