Is it possible to access Nuxt runtimeConfig values using $config in place of process.env in a stand-alone axios service file?

1.7k Views Asked by At

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)
  }
}
1

There are 1 best solutions below

0
Igor Sushko On

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.