Blog>
Snippets

Environment Variables for Configuration

Demonstrate how to use environment variables in a Vue.js 3 application for configuration purposes, allowing different settings for development, testing, and production environments.
// In a Vue.js 3 application, create a .env file at the root of your project
VUE_APP_API_URL=https://dev.api.example.com
VUE_APP_FEATURE_FLAG=true
This is the .env file containing environment variables for the development environment. The variables are prefixed with VUE_APP_ which is a requirement by Vue.js so it knows to include them in the process.env object.
// .env.production
VUE_APP_API_URL=https://prod.api.example.com
VUE_APP_FEATURE_FLAG=false
This .env.production file contains environment variables specific to the production environment. These variables will be used when you build your application for production.
// .env.test
VUE_APP_API_URL=https://test.api.example.com
VUE_APP_FEATURE_FLAG=true
This .env.test file is for the testing environment. Setting these variables allows you to run tests with settings that mirror the test environment closely.
// vue.config.js
module.exports = {
  devServer: {
    proxy: process.env.VUE_APP_API_URL,
  },
  configureWebpack: {
    // ... other configuration
  }
};
The vue.config.js file can use the environment variables to configure the webpack dev server, among other settings. Here the API URL is used to set up a proxy for development purposes.
// In your Vue.js components or store
export default {
  data() {
    return {
      apiUrl: process.env.VUE_APP_API_URL,
      featureFlag: process.env.VUE_APP_FEATURE_FLAG === 'true',
    };
  }
};
This piece of code within a Vue.js component or store demonstrates how to access and use environment variables. The process.env object contains all environment variables starting with VUE_APP_.
// console.log(process.env);
// { VUE_APP_API_URL: 'https://dev.api.example.com', VUE_APP_FEATURE_FLAG: 'true' }

console.log(`API URL: ${process.env.VUE_APP_API_URL}`);
console.log(`Feature Flag is enabled: ${process.env.VUE_APP_FEATURE_FLAG}`);
This is an example of logging the environment variables to the console. In actual code, you would use the environment variables without logging, but this serves as an illustration of accessing them.
/* package.json */
{
  // ...
  "scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build",
    "build:prod": "vue-cli-service build --mode production",
    "build:test": "vue-cli-service build --mode test",
    "test": "vue-cli-service test:unit"
  }
}
In the package.json file, you can specify scripts that use different modes when serving or building the application. This uses vue-cli-service to apply the correct .env file based on the specified mode.