1

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)

5
  • The environment variables are available at the runtime of where the build is executed. You can't have an environment variable be exported to the bundle that is executed in the (browser) client because that is executed in the browser. Commented Mar 28, 2018 at 23:38
  • @acdcjunior I understand that the only time I can have access to the env vars is the build time. But isn't that possible to bake them at this moment in the resulting build? If so I'll be forced to use some hacks in my Dockerfile... Commented Mar 29, 2018 at 15:57
  • Are you using vue-cli? If so, what version? Commented Mar 29, 2018 at 16:32
  • @acdcjunior I do. vue -V says it's 2.9.3 Commented Mar 29, 2018 at 21:10
  • I have tested adding to config/dev.env.js and it worked for me. Have you tried it in a brand new cli project? Commented Apr 1, 2018 at 1:42

2 Answers 2

1

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)
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.