3

In my nuxt 3 App, for data fetching I wanna set a baseURL for all my API calls. As I get this baseURL from enviroment variable. How to set the the baseURL?

I warp the useFetch with composables, but then I can't get the baseURL as useRuntimeConfig() is not accessable there.

// My composables function
const baseURL = "how to get baseURL from process.env";

export const myFetch = async (url: string) => {
  const options = {
    baseURL: baseURL,
  };

  return await useFetch(url, options);
}
kissu
  • 40,416
  • 14
  • 65
  • 133
nur_riyad
  • 1,091
  • 6
  • 21
  • 1
    Here is a comment that may be relevant in your case: https://github.com/nuxt/framework/discussions/3215#discussioncomment-3088206 Otherwise, the rest of the discussion is also interesting. – kissu Aug 02 '22 at 12:36
  • Thanks a lot. It working. I just have to declear the `useRuntimeConfig()` inside my composable function – nur_riyad Aug 02 '22 at 14:45
  • Posted an answer! – kissu Aug 02 '22 at 19:06

1 Answers1

3

You can access the runtime config by doing so

export default () => {
  const config = useRuntimeConfig()

  console.log(config)
}

As shown here: https://github.com/nuxt/framework/discussions/3215#discussioncomment-3088206

kissu
  • 40,416
  • 14
  • 65
  • 133
  • 1
    anyone know how to do this in Nuxt 2? – v3nt Apr 04 '23 at 16:00
  • @v3nt if I'm not mistaken, there are no composable in Nuxt2. – kissu Apr 04 '23 at 19:12
  • there are is you use composition api – v3nt Apr 05 '23 at 10:08
  • Yeah I would also be interested in how I can use this with nuxt 2.17, nuxt-bridge and the composition-api – Merc Jul 26 '23 at 12:45
  • @Merc https://stackoverflow.com/a/67705541/8816585 – kissu Jul 26 '23 at 13:31
  • Thanks for the link. It does not really cover how I can use useRuntimeConfig in my vuex store though. I tried but I get errors all the time... – Merc Jul 26 '23 at 13:51
  • @Merc you should rather be using Pinia anyway. Feel free to post a brand new question. – kissu Jul 26 '23 at 19:09
  • I am moving away from vuex anyway. Instead of Pinia I use composables now to manage (shared) states. I have an older project where we still work with vuex but I needed to overhaul the project and update and now my nuxt.config includes `runtimeConfig` AND `env`. The latter to still have access to my env variables in a vuex store module. I wanted to get rid of that. Maybe someday I will remove the vuex store completely. – Merc Jul 27 '23 at 08:49