Configuration

Rationale

Proper configuration management improves security, flexibility, and maintainability. It allows for easy environment changes and protects sensitive data.

Environment Variables

Use environment variables for secrets and environment-specific values. Store them in a .env file and never commit secrets to version control.

Example (.env):

API_URL=https://api.example.com
DB_PASSWORD=supersecret
DEBUG=false

Good Usage:

// Good: Load env variables with dotenv
require('dotenv').config();
const apiUrl = process.env.API_URL;

Bad Usage:

// Bad: Hardcoded secrets
const apiUrl = 'https://api.example.com';
const dbPassword = 'supersecret';
  • Never commit .env files with secrets to version control.
  • Use default values for non-sensitive settings.

Config Files

Centralize configuration in a config/ directory. Validate configuration values before use and document all required config options for new team members.

Example:

// config/app.js
module.exports = {
  apiUrl: process.env.API_URL || 'https://api.example.com',
  debug: process.env.DEBUG === 'true',
};
  • Group related settings in separate config files (e.g., config/db.js, config/app.js).
  • Validate configuration before use and throw errors for missing required values.

Best Practices

  • Document configuration structure and usage.
  • Use default values and validation for config options.
  • Keep sensitive data out of source code.
  • Separate development, staging, and production configs.
  • Document all required config options for new team members.
  • Regularly review and update configuration for security and maintainability.