Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VueJS & Webpack: ENV var unaccessible from built project

I'm working on an app with vuejs frontend and nodejs backend. My frontend makes API https requests to the backend. I've started my projet with vue-cli and webpack. I need to get the backend API url from env variable (BACKEND_URL). Since i'm using webpack, I added this line to config/prod.env.js :

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

It works flawlessly in dev mode using webpack-dev-server. I pass the env var throught docker-compose file:

environment:
            - BACKEND_URL=https://whatever:3000

But when I run build, I use nginx to serve the static files (but the problem is the same using visual studio code live server extension). I send BACKEND_URL env var the same way as before. The thing is now the process.env.BACKEND_URL is undefined in the app (but defined in the container)!! So I cant make backend http calls :( I'm struggling finding the problem, please don't be rude with the responses. Thank you

like image 477
Morgan Le Floc'h Avatar asked Jan 28 '23 02:01

Morgan Le Floc'h


2 Answers

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.

like image 115
PlayMa256 Avatar answered Jan 31 '23 07:01

PlayMa256


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.

like image 23
brandon-barnett Avatar answered Jan 31 '23 07:01

brandon-barnett