Vue.js Environment Variables
When building a Vue.js application for deployment, you'll often need different configurations based on the environment where your application is running. Environment variables provide a way to manage these configurations securely and effectively.
What Are Environment Variables?
Environment variables are dynamic values that can affect the way running processes behave on a computer. In web development, they allow you to:
- Store sensitive information like API keys separately from your code
- Configure different settings for development, testing, and production environments
- Change application behavior without modifying the codebase
Why Use Environment Variables in Vue.js?
Using environment variables in your Vue.js projects offers several advantages:
- Security: Keep sensitive information like API keys out of your source code
- Environment-specific configuration: Maintain different settings for development, staging, and production
- Simplified deployment: Deploy the same code to different environments with environment-specific configurations
- Better team collaboration: Team members can have their own local configurations
Environment Variables in Vue CLI Projects
Vue CLI provides built-in support for environment variables through .env
files.
Basic Setup
- Create environment files in your project root:
├── .env # loaded in all environments
├── .env.local # loaded in all environments, ignored by git
├── .env.development # only loaded in development environment
├── .env.production # only loaded in production environment
- Add variables to these files using the format:
VUE_APP_API_URL=https://api.example.com
VUE_APP_DEBUG=true
In Vue CLI projects, only variables that begin with VUE_APP_
will be embedded in your application bundle!
Accessing Environment Variables
You can access these variables in your Vue components:
// Using in a component
export default {
mounted() {
console.log(process.env.VUE_APP_API_URL);
console.log(process.env.VUE_APP_DEBUG);
}
}
Or in your Vue templates:
<template>
<div>
<p>API URL: {{ process.env.VUE_APP_API_URL }}</p>
<p v-if="process.env.VUE_APP_DEBUG">Debug mode is ON</p>
</div>
</template>
Environment Variables in Vite Projects
If you're using Vite (Vue 3's recommended build tool), the process is slightly different.
Basic Setup for Vite
- Create
.env
files similar to Vue CLI:
├── .env # loaded in all environments
├── .env.local # loaded in all environments, ignored by git
├── .env.development # only loaded in development environment
├── .env.production # only loaded in production environment
- Add variables with the format:
VITE_API_URL=https://api.example.com
VITE_DEBUG=true
In Vite projects, only variables prefixed with VITE_
are exposed to your client-side code!
Accessing Variables in Vite Projects
Access these variables in your components:
// Using in a component
export default {
mounted() {
console.log(import.meta.env.VITE_API_URL);
console.log(import.meta.env.VITE_DEBUG);
}
}
Or in your templates:
<template>
<div>
<p>API URL: {{ import.meta.env.VITE_API_URL }}</p>
<p v-if="import.meta.env.VITE_DEBUG">Debug mode is ON</p>
</div>
</template>
Environment Variable Priority
The order of precedence for environment files is:
Where [mode]
is the current environment (development
, production
, or test
).
Real-World Examples
Configuring API Endpoints
A common use case is configuring different API endpoints for development and production:
.env.development
VUE_APP_API_URL=http://localhost:3000/api
.env.production
VUE_APP_API_URL=https://api.myproduct.com/v1
ApiService.js
import axios from 'axios';
const apiClient = axios.create({
baseURL: process.env.VUE_APP_API_URL,
timeout: 10000,
headers: {
'Content-Type': 'application/json'
}
});
export default {
getUsers() {
return apiClient.get('/users');
},
getUserById(id) {
return apiClient.get(`/users/${id}`);
}
// Other API methods...
};
Feature Flags
Use environment variables to enable/disable features:
.env.development
VUE_APP_FEATURE_NEW_UI=true
VUE_APP_ENABLE_ANALYTICS=false
.env.production
VUE_APP_FEATURE_NEW_UI=false
VUE_APP_ENABLE_ANALYTICS=true
App.vue
<template>
<div>
<NewUI v-if="isNewUIEnabled" />
<LegacyUI v-else />
<analytics-tracker v-if="analyticsEnabled" />
</div>
</template>
<script>
import NewUI from './components/NewUI.vue';
import LegacyUI from './components/LegacyUI.vue';
import AnalyticsTracker from './components/AnalyticsTracker.vue';
export default {
components: {
NewUI,
LegacyUI,
AnalyticsTracker
},
data() {
return {
isNewUIEnabled: process.env.VUE_APP_FEATURE_NEW_UI === 'true',
analyticsEnabled: process.env.VUE_APP_ENABLE_ANALYTICS === 'true'
}
}
}
</script>
Best Practices
- Never commit sensitive information: Add
.env.local
and.env.*.local
to your.gitignore
file - Document required variables: Include a
.env.example
file with dummy values to document required variables - Validate environment variables: Check for required variables when your app starts
- Minimize client-exposed variables: Only expose what's necessary to the client
- Use typed environment variables: Convert strings to appropriate types when accessing them
Example of validating required variables:
// src/utils/validateEnv.js
export default function validateEnv() {
const requiredVars = ['VUE_APP_API_URL'];
const missing = requiredVars.filter(
varName => !process.env[varName]
);
if (missing.length > 0) {
throw new Error(
`Missing required environment variables: ${missing.join(', ')}`
);
}
}
// src/main.js
import validateEnv from './utils/validateEnv';
// Validate environment variables before starting app
validateEnv();
// Initialize Vue app
// ...
Environment Variables in Deployment Platforms
Different deployment platforms handle environment variables differently:
Netlify
Set environment variables in the Netlify UI under Site settings > Build & deploy > Environment variables
For local development with Netlify CLI, create a .env
file and use the -e
flag:
netlify dev -e .env.local
Vercel
Set environment variables in the Vercel UI under Project Settings > Environment Variables
You can also set variables for different environments (production, preview, development).
Docker
Pass environment variables when running a container:
docker run -e VUE_APP_API_URL=https://api.example.com my-vue-app
Or use a docker-compose.yml
file:
version: '3'
services:
app:
build: .
environment:
- VUE_APP_API_URL=https://api.example.com
- VUE_APP_DEBUG=false
Summary
Environment variables are essential for configuring Vue.js applications across different environments. They help keep sensitive information out of your source code and enable environment-specific configurations.
Key takeaways:
- Use
.env
files to define environment variables - Prefix variables with
VUE_APP_
for Vue CLI projects orVITE_
for Vite projects - Never commit sensitive information to your code repository
- Use environment variables for API endpoints, feature flags, and other configuration settings
- Configure environment variables appropriately for your deployment platform
Additional Resources
- Official Vue CLI Environment Variables Documentation
- Vite Env Variables Documentation
- 12 Factor App - Config - Best practices for application configuration
Exercises
- Create a Vue application with different API endpoints for development and production.
- Implement feature flags that enable/disable certain features based on the environment.
- Set up environment-specific logging that only shows debug information in development.
- Configure environment variables for a third-party service like Google Maps or Firebase.
- Create a configuration validation system that checks for required environment variables at startup.
If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)