1

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?

morteza mortezaie
  • 1,002
  • 14
  • 37

2 Answers2

0

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.

kissu
  • 40,416
  • 14
  • 65
  • 133
-1

your .env file should like this

BASE_URL= "http://www.a.com/"

and your nuxt.config like this

runtimeConfig: {
    public: {
      BASE_URL: process.env.BASE_URL,
    }
},

then add this to your service file

import axios from 'axios'

const http = axios.create({
    baseURL: useRuntimeConfig().BASE_URL,
})
export default http