Dynamic environment variables in VueJS

Suppose you need an app based in an API to fetch the data, and we have 3 different development stages Test, Dev and Prod.

What we want is, based upon on the staging environment, the app can call the right API and don’t want to deploy our app every time we change between stages or change URLs.

For this, we will create a new file /static/config.json in our statics folder. The example file will have the URL used by default:

Now in Vue app where we use the URL, declare in created() function a false API GET call to that file, in this example, we use axios:

Now our app will fetch that URL dynamically, and we can change it later without the need to deploy it.

Well, now we have to create a file for every stage we need, in this case, we have 3 stages, so we need to create 3 files in the environments directory (plus the default created before), the example structure will be:

So, we have the 3 files for every stage (plus the default) and the app can call dynamically at the file to fetch the URL, now we have to make sure to copy the environment folder to the same destination when we deploy the app (npm run build). We can do this done in multiple automatic forms (CopyWebpackPlugin, npm run script…) or can we do it manually by copying the folder to the destination, in this example will use the CopyWebpackPlugin plugin, what let us copy files automatically by adding the following to our config file, in this case, /build/webpack.base.conf.js (change it based on your configuration):

Finally, our structure after deploy will be:

Now every time we deploy our app, we have to make sure to replace /static/config.json with the right environment file, we can do this manually or if we have any CI (Continuous Integration) process such as Jenkins, we can configure it to automatically copy the right file based on deployment stage.

Leave a Reply

Your email address will not be published. Required fields are marked *