How to use environment variables with Vue.js?

Sometimes, we want to use environment variables with Vue.js.

In this article, we’ll look at how to use environment variables with Vue.js.

How to use environment variables with Vue.js?

To use environment variables with Vue.js, we can add an .env file with the variable keys starting with VUE_APP.

For instance, we write

VUE_APP_MY_ENV_VARIABLE=value
VUE_APP_ANOTHER_VARIABLE=value

Then we can access them in our app with

process.env.VUE_APP_MY_ENV_VARIABLE
process.env.VUE_APP_ANOTHER_VARIABLE

This works if the app is created with Vue CLI.

We can specify .env files with different extensions for different environments.

For instance, we can have

.env                # loaded in all cases
.env.local          # loaded in all cases, ignored by git
.env.[mode]         # only loaded in specified mode
.env.[mode].local   # only loaded in specified mode, ignored by git

Then we can use npm run serve --mode=[mode] to run the Vue project with the given config.

Conclusion

To use environment variables with Vue.js, we can add an .env file with the variable keys starting with VUE_APP.