VueJS & Webpack: ENV var unaccessible from built project VueJS & Webpack: ENV var unaccessible from built project vue.js vue.js

VueJS & Webpack: ENV var unaccessible from built project


They aren not "translated" during build time, this is what is happening with you. On a node environment, when you ask for process.env it will show all environment variables available in the system, that is true. But a web application does not have access to process.env when it is executing. You need a way to translate them during build time.

To achieve that you have to use DefinePlugin. It translates anything during build time and writes a magical string where this other thing was.

Using you own example:

module.exports = {  NODE_ENV: '"production"',  BACKEND_URL: JSON.stringify(process.env.BACKEND_URL)}

If you do this during build time, without DefinePlugin, webpack won't know what to do with it, and it is going to be a simple string.

If you use DefinePlugin:

new webpack.DefinePlugin({  "process.env.BACKEND_URL": JSON.stringify(process.env.BACKEND_URL)});

By doing this, you are allowing webpack to translate this during build time.


Give this a shot: https://www.brandonbarnett.io/blog/2018/05/accessing-environment-variables-from-a-webpack-bundle-in-a-docker-container/

If I'm understanding your problem correctly, you're serving a webpack bundle using nginx, and trying to access an environment variable from that bundle.

Unfortunately, it doesn't quite work that way. Your JS file has no access to the environment since it's a resource that has been delivered to the client. I've proposed a solution that also delivers those env variables alongside the bundle in a separate JS file that gets created on container start.


From VueJS Docs: https://cli.vuejs.org/guide/mode-and-env.html

Using Env Variables in Client-side Code

Only variables that start with VUE_APP_ will be statically embedded into the client bundle with webpack.DefinePlugin. You can access them in your application code:

console.log(process.env.VUE_APP_SECRET)

During build, process.env.VUE_APP_SECRET will be replaced by the corresponding value. In the case of VUE_APP_SECRET=secret, it will be replaced by "secret".


So in your case, the following should do the trick. I had the same problem once in my project, which I started with vue/cli and vue create project ...

VUE_APP_BACKEND_URL=https://whatever:3000