Shawn Wilson
Shawn Wilson

Reputation: 1351

properly use ENV Variables in vue-cli

So I'm brand freaking new to Vue-Cli and I'm following a tutorial on using a Vue frontend with a Rails backend. Im configuring Axios to handle my requests.

My problem:

Im trying to set an ENV_VAR on my API_URL constant, at this point when I try to console.log the API_URL I get the following error:

Uncaught ReferenceError: process is not defined
at <anonymous>:1:13

I have the following to config/dev.env.js

'use strict'
const merge = require('webpack-merge')
const prodEnv = require('./prod.env')

module.exports = merge(prodEnv, {
  NODE_ENV: '"development"',
  ENV_API_URL: '"http://localhost:3000/api/fuzeisp/v1"'
})

and I am trying to call that ENV in src/backend/axios/index.js import axios from 'axios'

const API_URL = process.env.ENV_API_URL

const securedAxiosInstance = axios.create({
  baseURL: API_URL,
  withCredentials: true,
  headers: {
    'Content-Type': 'application.json'
  }
})

I have tried to read the docs, but for some reason i cant make heads or tails of this! any assistance here would be greatly appreciated! Please, If you need more information i would be happy to provide it for you!

Thanks in advance.

Upvotes: 1

Views: 1493

Answers (2)

MarcRo
MarcRo

Reputation: 2473

The vue cli is using the dotenv to parse .env files with their content, adding their content to the process.env object. However, these variables will only be available at build-time (since process.env is a global property of the node environemnt).

Code at client-side will not have access to the process object at all. However, vue cli helps out! It reads process.env variables at build time and replaces them with their corresponding values - so you can use them in your client side code. NOTE: It only replaces those variables prepended with VUE_APP_; e.g. VUE_APP_BASE_URL=www.myapp.com.

Read more about it here

Upvotes: 1

Shawn Wilson
Shawn Wilson

Reputation: 1351

so I was able to log the output of VUE_APP_ENV_API_URL by adding the following in my App.vue file:

<script>
export default {
  name: 'App',
  mounted () {
    console.log(process.env.VUE_APP_ENV_API_URL)
  }
}
</script>

Upvotes: 0

Related Questions