Module: Vue Deployment and Best Practices

Environment variables

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: .env files store key-value pairs. The dotenv package loads these variables into process.env during development.
  • Installation:
    npm install dotenv --save-dev
    # or
    yarn add dotenv --dev
    
  • Usage:
    • Create .env files (e.g., .env.development, .env.production, .env.local). .env.local is typically for local overrides and should not be committed.
    • Add variables to your .env file:
      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
      
  • Important: Variables in .env files must be prefixed with VUE_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 your vue.config.js).
  • .env file 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.js file. 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 .env files 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.env in 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.

Deployment Best Practices

  • Never Commit .env Files: Add .env to your .gitignore file to prevent accidental commits of sensitive information.
  • Use Server-Side Environment Variables in Production: Avoid using .env files in production environments. Configure environment variables directly on your server.
  • Separate Configurations: Use different .env files 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 via process.env in 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 declare module to define the process.env types.

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.