🍋
Menu
Best Practice Beginner 1 min read 248 words

Environment Variable Management Best Practices

Environment variables separate configuration from code, enabling the same application to run in development, staging, and production. Learn secure patterns for managing them.

The Twelve-Factor Approach

The Twelve-Factor App methodology stores configuration in environment variables. This separates secrets and deployment-specific settings from code, preventing accidental commits of API keys and enabling the same codebase to run across environments.

.env Files for Local Development

Use a .env file for local development, loaded by your application framework. Include .env in .gitignore to prevent secrets from reaching version control. Provide a .env.example with placeholder values documenting all required variables.

Required vs Optional Variables

Validate all required environment variables at application startup. Fail fast with a clear error message listing missing variables rather than crashing deep in business logic when a variable is first accessed. For optional variables, define sensible defaults in code.

Secret Management in Production

Never store secrets in environment variables on disk (.bashrc, docker-compose.yml). Use a secrets manager — AWS Secrets Manager, HashiCorp Vault, 1Password, or your platform's native secrets store. Inject secrets at runtime, not build time. Rotate secrets regularly and audit access.

Naming Conventions

Use SCREAMING_SNAKE_CASE for environment variables. Prefix with your application name to avoid conflicts: MYAPP_DATABASE_URL. Group related variables: MYAPP_SMTP_HOST, MYAPP_SMTP_PORT, MYAPP_SMTP_USER. Use _URL suffixes for connection strings that combine host, port, credentials, and database name.

Common Pitfalls

Don't use environment variables for complex structured data — they're strings, not JSON objects. Don't share the same secrets across environments. Don't log environment variables at startup (leaks secrets). Don't use environment variables for feature flags — use a dedicated feature flag service instead.

関連ツール

関連フォーマット

関連ガイド