Environment Variables in Vue.js: Deployment & Best Practices
Environment variables are crucial for managing different configurations across development, staging, and production environments without hardcoding sensitive information directly into your codebase. This document outlines how to effectively use environment variables in your Vue.js projects, focusing on deployment best practices.
Why Use Environment Variables?
- Security: Avoid committing sensitive data like API keys, database passwords, and secret tokens to your version control system.
- Configuration Management: Easily switch between different configurations (e.g., different API endpoints for development and production) without modifying code.
- Portability: Make your application more portable and adaptable to different environments.
- Maintainability: Centralize configuration, making it easier to update and manage.
Methods for Using Environment Variables in Vue.js
There are several approaches to using environment variables in Vue.js, each with its pros and cons.
1. .env Files with dotenv (Recommended for Development)
- How it works:
.envfiles store key-value pairs. Thedotenvpackage loads these variables intoprocess.envduring development. - Installation:
npm install dotenv --save-dev # or yarn add dotenv --dev - Usage:
- Create
.envfiles (e.g.,.env.development,.env.production,.env.local)..env.localis typically for local overrides and should not be committed. - Add variables to your
.envfile:VUE_APP_API_URL=http://localhost:3000/api VUE_APP_DEBUG=true - Access variables in your Vue code:
console.log(process.env.VUE_APP_API_URL); console.log(process.env.VUE_APP_DEBUG === 'true'); // Convert to boolean if needed
- Create
- Important: Variables in
.envfiles must be prefixed withVUE_APP_to be accessible in the browser-side Vue code. This is a security measure to prevent accidental exposure of server-side secrets. Variables without the prefix are only available during server-side build processes (e.g., in yourvue.config.js). .envfile precedence:.env.local>.env.development/.env.production>.env
2. vue.config.js (For Build-Time Configuration)
- How it works: You can access environment variables directly within your
vue.config.jsfile. This is useful for configuring build processes, such as setting the output directory or defining custom webpack configurations. - Usage:
// vue.config.js module.exports = { publicPath: process.env.VUE_APP_PUBLIC_PATH || '/', configureWebpack: { devtool: process.env.NODE_ENV !== 'production' ? 'source-map' : null, } }; - Note: Variables accessed here do not need the
VUE_APP_prefix. They are only used during the build process and are not exposed to the browser.
3. Server-Side Environment Variables (For Production)
- How it works: In production, you should not rely on
.envfiles directly. Instead, set environment variables directly on your server (e.g., using your hosting provider's control panel, Docker Compose, Kubernetes, or server configuration files). - Accessing in Node.js Backend (if applicable): If you have a Node.js backend serving your Vue.js frontend, you can access these variables using
process.envin your backend code. - Passing to Vue Frontend (via API): The most secure approach is to have your backend API expose the necessary configuration values to your Vue.js frontend. This avoids exposing sensitive information directly in the browser. For example:
- Backend API endpoint:
/api/config - Response:
{ apiUrl: process.env.API_URL, featureFlag: process.env.FEATURE_FLAG } - Vue.js fetches this data on application startup.
- Backend API endpoint:
Deployment Best Practices
- Never Commit
.envFiles: Add.envto your.gitignorefile to prevent accidental commits of sensitive information. - Use Server-Side Environment Variables in Production: Avoid using
.envfiles in production environments. Configure environment variables directly on your server. - Separate Configurations: Use different
.envfiles for different environments (development, staging, production). - Secure Your Server: Ensure your server is properly secured to protect your environment variables.
- Consider a Secrets Manager: For complex deployments, consider using a secrets manager (e.g., AWS Secrets Manager, HashiCorp Vault) to securely store and manage your sensitive data.
- Build-Time vs. Runtime Variables: Understand the difference. Build-time variables (accessed in
vue.config.js) are baked into the application during the build process. Runtime variables (accessed viaprocess.envin the browser) are loaded at runtime. Favor runtime variables for configuration that might change without a rebuild. - Type Safety (TypeScript): If using TypeScript, define types for your environment variables to catch errors during development. Use a
declaremodule to define theprocess.envtypes.
Example .env.development
VUE_APP_API_URL=http://localhost:3000/api
VUE_APP_DEBUG=true
VUE_APP_FEATURE_FLAG=false
Example .env.production
VUE_APP_API_URL=https://api.example.com
VUE_APP_DEBUG=false
VUE_APP_FEATURE_FLAG=true
Summary
Using environment variables effectively is essential for building secure, maintainable, and portable Vue.js applications. By following these best practices, you can ensure that your application is properly configured for each environment and that sensitive information is protected. Remember to prioritize server-side configuration in production and avoid committing .env files to your repository.