isebarn
isebarn

Reputation: 3940

Nuxt + Vue + Axios + Enviroment Variables

I am unable to provide axios a baseUrl using an enviroment variable

I am using nuxt/vue/axios

What I have is roughly:

// axios.js

import Vue from 'vue'
import axios from 'axios'
import VueAxios from 'vue-axios'

axios.defaults.baseURL = process.env.BASE_URL
Vue.use(VueAxios, axios)

and

// index.vue (front page as it appears on the client)

populateFilters () {
  Vue.axios.get('filters').then((response) => {
    this.$store.commit('data/filters', response.data)
  })
    .catch((e) => {
      console.error(e)
    })
}

and inside nuxt.config.js

  // nuxt.config.js
  build: {
    extractCSS: true,
    extend (config, ctx) {
    // Run ESLint on save

    const envLoad = require('dotenv').config()

    if (envLoad.error){
      throw result.error
    }
  }
},

console.log(process.env.BASE_URL) prints the correnct connection string in CMD, however, in chrome web browser it outputs "undefined" and I get the following error

GET http://localhost:3000/filters 404 (Not Found)

meaning that axios (probably) defaults to http://localhost:3000 whenever the baseUrl for axios has not been set.

What I think the problem is

The server/client pair that is loaded up by nuxt has different contexts or that the server loads up axios before the enviroment variables have been loaded

What I need

I need to be able to either:

  1. create .env files that contains (amongst other things) the BASE_URL
  2. define these enviroment variables somewhere in the code (nuxt.config.js ?)

Solution Please see the accepted answer

In addition, install nuxtjs/dotenv

npm install @nuxtjs/dotenv

and make your nuxt.config.js look like:

  // nuxt.config.js
  require('dotenv').config()

  module.exports = {

  modules: [
  '@nuxtjs/dotenv',
      '@nuxtjs/axios',
  ],

  axios: {
    baseURL: process.env.BASE_URL
  },
}

note that require('dotenv').config() must be at the top

Upvotes: 2

Views: 3877

Answers (1)

Pjotr Raskolnikov
Pjotr Raskolnikov

Reputation: 1688

Theres a nuxt axios module you can use. You can declare it in the module sectiont of your nuxt.config.js so you dont need your file axios.js. This is described here https://github.com/nuxt-community/axios-module#usage

By loading it in the modules in the nuxt.config.js file you will have your axios instance accesible with this.$axios in your components.

You can declare the base url in the nuxt.config.js

modules: [
    // Doc: https://github.com/nuxt-community/axios-module#usage
    ['@nuxtjs/axios', {
      baseURL: 'http://jsonplaceholder.typicode.com'
    }]
  ],
  /*
  ** Axios module configuration
  */
  axios: {
    // See https://github.com/nuxt-community/axios-module#options
  },

For "other environement variables" you can use the vuex store to have them available to all components.

Upvotes: 1

Related Questions