1

Making the transition from using dotenv to Nuxt runtimeconfig. Is it possible to access Nuxt runtimeConfig values using $config in place of process.env in a stand-alone axios service file, something like the following:

userService.js

import axios from 'axios'

const apiClient = axios.create({
  baseURL: context.$config.baseURL, // <-- want to do this (or similar)
  withCredentials: false,
  headers: {
    Accept: 'application/json',
    'Content-Type': 'application/json'
  }
})

export default {
  createCCWUser(userData) {
    return apiClient.post('/users', userData)
  },
  updateCCWUser(updatedUserData) {
    return apiClient.put('/users/' + updatedUserData.id, updatedUserData)
  }
}
kissu
  • 40,416
  • 14
  • 65
  • 133
  • What is the problem you are seeing while using *context.$config.baseURL*? Is this.$config.baseURL working instead? (I am also using runtime config for my app) – Naveen Karnam Aug 12 '20 at 17:12
  • I've tried both, and in the context of this file, both come back with $config undefined. With dotenv installed, process.env.BASE_URL works as expected. – user3665916 Aug 13 '20 at 18:08
  • Well, process.env.* works in the app. But in the nuxt.config.js, I think the assignment is not successful even with dotenv installed. Let me try this again under any case. – Naveen Karnam Aug 14 '20 at 01:08
  • You are right @user3665916. I checked this again. $config for me is showing the keys I define on nuxt.config.js but the values are showing 'undefined'. The reason we are OK with referring process.env in nuxt.config.js but not in the app? Because we want env to pass on to app during build time which may happen on any CI build server. On production server, we don't want to rely on process.env for runtime configuration. Here's my question on this. https://stackoverflow.com/q/63381773/2477612 – Naveen Karnam Aug 14 '20 at 06:45

1 Answers1

0

Maybe it can possible with serverMiddleware. you need add in nuxt.config.js serverMiddleware option and specify path to your axios service. Then in this server you maybe have access, because serverMiddleware start before nuxt rendering.