Environment Variables and Configuration
Managing configuration and environment variables in Node.js applications
Challenge
Section titled “Challenge”Your application needs different configurations for development, staging, and production. You need to securely manage sensitive data like API keys and database credentials. How do you organize this?
Explanation
Section titled “Explanation”Environment variables are the standard way to configure Node.js applications. Using .env files during development and environment variables in production is a best practice.
Solution: Environment Management
Section titled “Solution: Environment Management”// .env fileDATABASE_URL=postgresql://localhost/mydbAPI_KEY=your-secret-key-hereNODE_ENV=developmentLOG_LEVEL=debug
// Load .env file (using dotenv package)require('dotenv').config();
// Access environment variablesconst dbUrl = process.env.DATABASE_URL;const apiKey = process.env.API_KEY;const env = process.env.NODE_ENV || 'development';
// Validate required variablesconst required = ['DATABASE_URL', 'API_KEY'];const missing = required.filter(key => !process.env[key]);
if (missing.length > 0) { throw new Error(`Missing required env vars: ${missing.join(', ')}`);}Configuration Management
Section titled “Configuration Management”module.exports = { development: { database: 'sqlite::memory:', cacheEnabled: false, logLevel: 'debug' }, staging: { database: process.env.DATABASE_URL, cacheEnabled: true, logLevel: 'info' }, production: { database: process.env.DATABASE_URL, cacheEnabled: true, logLevel: 'warn', ssl: true }};
// app.jsconst config = require('./config')[process.env.NODE_ENV || 'development'];console.log('Database:', config.database);console.log('Cache enabled:', config.cacheEnabled);Secrets Management
Section titled “Secrets Management”.env.env.local.env.*.local
// Use different .env files per environment.env # Shared defaults.env.development # Dev overrides.env.production # Prod overrides (NOT in git).env.example # Template for required vars
// Accessing secrets safelyconst apiKey = process.env.API_KEY;if (!apiKey) { throw new Error('API_KEY not configured');}
// Never log secretsconsole.log({ apiKey: '***' }); // Goodconsole.log({ apiKey }); // Bad