How to set global api baseURL used in useFetch in nuxt 3

Viewed 2136

How do I set the baseURL that is used in useFetch composable globally (maybe nuxt.config.ts) so that I wouldn't have to define it in every useFetch.

4 Answers

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.

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 to have the full blown version with types it's a bit longer:

// /composables/useMyFetch.ts

import { UseFetchOptions } from '#app'
import { NitroFetchRequest } from 'nitropack'
import { KeyOfRes } from 'nuxt/dist/app/composables/asyncData'

export function useMyFetch<T>(
  request: NitroFetchRequest,
  opts?:
    | UseFetchOptions<
        T extends void ? unknown : T,
        (res: T extends void ? unknown : T) => T extends void ? unknown : T,
        KeyOfRes<
          (res: T extends void ? unknown : T) => T extends void ? unknown : T
        >
      >
    | undefined
) {
  const config = useRuntimeConfig()

  return useFetch<T>(request, {
    baseURL: config.public.baseURL,
    ...opts,
  })
}

You can then use useMyFetch as replacement for useFetch - but with baseURL being set :-)

For anyone still looking for the answer to the original question you can do this in nuxt.config with runtimeConfig and env variables. You can of course replace the env variables with a hard-coded values if you prefer.

In your nuxt.config.js/ts

runtimeConfig: {
    SOME_SECRET_KEY: process.env.SOME_SECRET_KEY,
    public: {
      SOME_API_KEY: process.env.SOME_API_KEY,
    },
  },

Then in someComposable.js:

const config = useRuntimeConfig();

You can then access your variables as eg config.public.SOME_API_KEY

Hope that helps. More info here: https://v3.nuxtjs.org/guide/features/runtime-config

You can also involve .env like this

in .env

NUXT_PUBLIC_BASE_URL = https://www.someapi.com

in nuxt.config.js/ts

runtimeConfig: {
 
    public: {
      BASE_URL: 'some fallback value',
    },
  },

as it said in the document BASE_URL will be replaced by NUXT_PUBLIC_BASE_URL automatically

( no need to use process.env.NUXT_PUBLIC_BASE_URL )

and in composable you can use

const config = useRuntimeConfig();

console.log('base url is' , config.baseUrl)
Related