title: Nuxt + Vue + Axios + Enviroment Variables
body: <p>I am unable to provide axios a baseUrl using an enviroment variable</p>
  
  <p>I am using nuxt/vue/axios</p>
  
  <p>What I have is roughly:</p>
  
  <pre><code>// 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)
  </code></pre>
  
  <p>and </p>
  
  <pre><code>// index.vue (front page as it appears on the client)
  
  populateFilters () {
    Vue.axios.get('filters').then((response) =&gt; {
      this.$store.commit('data/filters', response.data)
    })
      .catch((e) =&gt; {
        console.error(e)
      })
  }
  </code></pre>
  
  <p>and inside nuxt.config.js</p>
  
  <pre><code>  // nuxt.config.js
    build: {
      extractCSS: true,
      extend (config, ctx) {
      // Run ESLint on save
  
      const envLoad = require('dotenv').config()
  
      if (envLoad.error){
        throw result.error
      }
    }
  },
  </code></pre>
  
  <p><code>console.log(process.env.BASE_URL)</code> prints the correnct connection string in CMD, however, in chrome web browser it outputs "undefined" and I get the following error</p>
  
  <pre><code>GET http://localhost:3000/filters 404 (Not Found)
  </code></pre>
  
  <p>meaning that axios (probably) defaults to <code>http://localhost:3000</code> whenever the baseUrl for axios has not been set.</p>
  
  <p><strong>What I think the problem is</strong></p>
  
  <p>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</p>
  
  <p><strong>What I need</strong></p>
  
  <p>I need to be able to either:</p>
  
  <ol>
  <li>create .env files that contains (amongst other things) the BASE_URL</li>
  <li>define these enviroment variables somewhere in the code (<code>nuxt.config.js</code> ?)</li>
  </ol>
  
  <p><strong>Solution</strong>
  Please see the accepted answer</p>
  
  <p>In addition, install nuxtjs/dotenv</p>
  
  <pre><code>npm install @nuxtjs/dotenv
  </code></pre>
  
  <p>and make your <code>nuxt.config.js</code> look like:</p>
  
  <pre><code>  // nuxt.config.js
    require('dotenv').config()
  
    module.exports = {
  
    modules: [
    '@nuxtjs/dotenv',
        '@nuxtjs/axios',
    ],
  
    axios: {
      baseURL: process.env.BASE_URL
    },
  }
  </code></pre>
  
  <p>note that <code>require('dotenv').config()</code> must be at the top</p>