Nuxt Axios Runtime Environment baseUrl

February 17, 2020
axios port issues: connect ECONNREFUSED 127.0.0.1:3000

If you just want to change axios baseUrl between development and production, you can easily use enviroment variable.

Edit nuxt.config.js

export default {
  modules: [
    '@nuxtjs/axios',
  ],
  axios: {
    baseURL: process.env.API_URL
  }
}

The limitation with this approach is that the configuration happened during build time. Assuming I want to change the baseUrl after build, depending on the runtime deployment environment (e.g. docker, firebase, etc.), it is not possible with the above approaching utilizing nuxt.config.js without a re-build.

Axios Runtime baseUrl

All configuration done via nuxt.config.js is build-time configuration. To enable runtime configuration, you need to utilize plugins.

Edit nuxt.config.js

export default {
  modules: [
    '@nuxtjs/axios',
  ],
  plugins: [
    '~/plugins/axios'
  ],
}

Edit plugins/axios.js.

export default function ({ $axios }) {
  $axios.setBaseURL(process.env.RUNTIME_API_URL || process.env.API_URL)
}

NOTE: Note that server runtime environment variables is only available on server by default. You might need to utilize vuex to pass server environment variables to client.

This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.