Environment Variables

Learn the proper way to manage secrets using environment variables and .env files. This is the recommended approach for most applications.

✅ Recommended Approach

Best Practice

Using environment variables is the industry standard for managing secrets. This approach keeps sensitive data separate from your codebase while maintaining flexibility across different deployment environments.

Proper Implementation

.env File (Not in Repository)

Environment variables stored in .env file (excluded from git)

.env File (Not in Repository) Snippet

1# .env - Keep this file secret and never commit it!
2DB_HOST=production.database.company.com
3DB_USERNAME=app_user
4DB_PASSWORD=SecureProductionPassword123!
5DB_PORT=5432
6
7# API Keys
8STRIPE_SECRET_KEY=sk_live_1234567890abcdef
9SENDGRID_API_KEY=SG.1234567890abcdef
10JWT_SECRET=super-secure-jwt-secret-key-production
11
12# External Services
13REDIS_URL=redis://user:pass@redis-server:6379
14AWS_ACCESS_KEY_ID=AKIAI1234567890ABCDEF
15AWS_SECRET_ACCESS_KEY=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY

Loading Environment Variables

Secure way to access secrets from environment variables

Loading Environment Variables Snippet

1// Load environment variables at the start of your application
2require('dotenv').config();
3
4// Database configuration using environment variables
5const dbConfig = {
6  host: process.env.DB_HOST,
7  username: process.env.DB_USERNAME,
8  password: process.env.DB_PASSWORD,
9  port: parseInt(process.env.DB_PORT)
10};
11
12// API Keys from environment
13const stripeKey = process.env.STRIPE_SECRET_KEY;
14const jwtSecret = process.env.JWT_SECRET;
15
16// Validate required environment variables
17if (!stripeKey) {
18  throw new Error('STRIPE_SECRET_KEY environment variable is required');
19}
20
21if (!jwtSecret) {
22  throw new Error('JWT_SECRET environment variable is required');
23}

Proper .gitignore Configuration

Essential .gitignore patterns to prevent secret exposure

Proper .gitignore Configuration Snippet

1# Environment files
2.env
3.env.local
4.env.development.local
5.env.test.local
6.env.production.local
7
8# Logs
9npm-debug.log*
10yarn-debug.log*
11yarn-error.log*
12
13# Runtime data
14pids
15*.pid
16*.seed
17*.pid.lock
18
19# Dependency directories
20node_modules/
21
22# Optional npm cache directory
23.npm
24
25# Output of 'npm pack'
26*.tgz
27
28# Secrets and certificates
29*.pem
30*.key
31secrets/
32config/secrets.yml

Deployment Platform Examples

Best Practices & Implementation Tips

Environment Validation

Always validate that required environment variables are present

Environment Validation Example

1const requiredEnvVars = ['DB_HOST', 'DB_PASSWORD', 'JWT_SECRET'];
2
3requiredEnvVars.forEach(envVar => {
4  if (!process.env[envVar]) {
5    throw new Error(`Missing required environment variable: ${envVar}`);
6  }
7});

Different Environments

Use different .env files for different environments

Different Environments Example

1# .env.development
2DB_HOST=localhost
3DB_PASSWORD=dev123
4DEBUG=true
5
6# .env.production  
7DB_HOST=prod.db.company.com
8DB_PASSWORD=SecureProductionPassword
9DEBUG=false

Fallback Values

Provide sensible defaults for non-sensitive configuration

Fallback Values Example

1const config = {
2  port: process.env.PORT || 3000,
3  nodeEnv: process.env.NODE_ENV || 'development',
4  dbHost: process.env.DB_HOST, // No fallback for secrets!
5  logLevel: process.env.LOG_LEVEL || 'info'
6};

Secret Documentation

Document required environment variables in README

Secret Documentation Example

1# Required Environment Variables
2
3## Database
4- `DB_HOST`: Database hostname
5- `DB_USERNAME`: Database username  
6- `DB_PASSWORD`: Database password
7
8## API Keys
9- `STRIPE_SECRET_KEY`: Stripe secret key
10- `JWT_SECRET`: JWT signing secret

CLI Demo (Terminal)

Run the environment variables demo from your terminal in this project root:

Run CLI demo

1# From project root
2node app-env.js
3
4# Or with Bun
5bun app-env.js

Interactive Demo & Guided Lab

This unified demo simulates secure environment variable management and walks through the guided lab steps. The output includes console logs, demo results, and lab scenario tasks and resources.

Rollout Plan

Kickoff

  • Inventory all services and credentials
  • Create .env.example documenting required variables
  • Agree on naming conventions and casing

Implementation

  • Add validation at application boot
  • Store secrets in platform-specific secret stores
  • Add scripts to sync secrets for developers

Sustainment

  • Schedule rotation and access reviews
  • Monitor for usage of default or placeholder values
  • Automate alerts for missing variables in deployments

Production-Grade Secret Management

While environment variables are great for most applications, enterprise applications should consider dedicated secret management solutions:

Cloud Providers:

  • AWS Secrets Manager
  • Azure Key Vault
  • Google Secret Manager

Self-Hosted Solutions:

  • HashiCorp Vault
  • Kubernetes Secrets
  • Docker Secrets

💡 Environment variables are perfect for getting started and most applications!

Source Code & Live Demo

See a complete implementation using environment variables with proper error handling:

Shared Secrets

Next: Learn industry best practices

Best Practices Guide