How to access Nuxt 3 runtimeConfig in service file?

Viewed 24

I have service file like this .

service/http.ts

import axios from 'axios'
const config = useRuntimeConfig()

const http = axios.create({
    baseURL: config.public.apiUrl,
})
export default http

and nuxt.config.js like this

export default defineNuxtConfig({
  runtimeConfig: {
    public: {
      apiUrl: 'some value',
    }
  },
});

and .env like this

NUXT_API_URL=http://www.a.com/

and I want to access apiUrl here .

But it gives me an error.

enter image description here

also if I use process.env.NUXT_API_URL .

it gives an error again

so, how can I access env variable for my services file?

1 Answers

Hm, I'm not sure but you may try that one.

import axios from 'axios'

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

  axios.create({
    baseURL: config.public.apiUrl,
  })
}

useRuntimeConfig() needs to be called inside of the function.

Related