Michael Miriti
Michael Miriti

Reputation: 322

Vue.js: Passing environment variables to a vue.js application

I'm running a vue.js application in a Docker container. I have some configuration set via environment variables (e.g. API base url). I want to be able to use these variables in my application in browser. How can I pass them?

I tried to add these variables to one of the config/*.env.js files like that (config/dev.env.js):

module.exports = merge(prodEnv, {
  NODE_ENV: '"development"',
  backendBase: process.env.BACKEND_BASE
})

Then I run application using npm run dev but process.env object is always empty (NODE_ENV is also not available)

Upvotes: 1

Views: 4211

Answers (2)

cam8001
cam8001

Reputation: 1641

I think only variables prefixed with VUE_APP get packaged up by Vue.

From: https://cli.vuejs.org/guide/mode-and-env.html#environment-variables

Note that only variables that start with VUE_APP_ will be statically embedded into the client bundle with webpack.DefinePlugin.

I tested locally.

.env in root:

APP_TEST=foo
VUE_APP_TEST=bar

In main.js:

// imports and other stuff

new Vue({
  render: h => h(App),
}).$mount('#app');

console.log(process.env.APP_TEST, 'APP_TEST');
console.log(process.env.VUE_APP_TEST, 'VUE_APP_TEST');

Output:

undefined APP_TEST 
bar VUE_APP_TEST 

You'll need to run another build if you make changes to your envvars.

Upvotes: 1

Gawth
Gawth

Reputation: 138

I came across the exact same problem recently. If you are running the dev server using a watcher I think it doesn't pick the config change up correctly. I stopped my dev server, rebuilt production as well (no idea if that helps but just in case) and then started the dev server up again and all was ok.

To access the above settings you should be able to use process.env in your code

console.log(process.env.NODE_ENV)

Upvotes: 1

Related Questions