Nuxt Axios Runtime Environment baseUrl

Feb 17, 2020
axios port issues: connect ECONNREFUSED

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.

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.