tezvyn:

Environment-Specific Config: Beyond Hardcoded Values

AI-drafted, machine-checkedSource: github.comintermediate

Think of config as layered transparencies: a base file sets defaults, and environment-specific files (like `production.json`) override them. This keeps database hosts and feature flags tidy across dev, staging, and prod.

WHY IT EXISTS: An application needs different settings for development (local DB, test keys) versus production (production DB, real keys). Hardcoding these values or using complex if/else blocks based on the NODE_ENV variable is brittle, error-prone, and makes configuration hard to manage.

THE MENTAL MODEL: Imagine a stack of configuration files. The bottom layer is a default.json file, containing every possible configuration key for your application. On top of that, you place a file corresponding to the current environment, like production.json. This top file only needs to contain the values that are different from the default. The application reads the default first, then merges the environment-specific file over it, creating the final, active configuration.

HOW IT WORKS: Libraries like node-config look for a config/ directory. On startup, they load config/default.json. Then, they check an environment variable like NODE_ENV. If NODE_ENV is set to "production", the library loads config/production.json and merges its properties on top of the default configuration. Any value in production.json overwrites the same value from default.json. Your application code then accesses these merged values through a simple API, like config.get('db.host').

WHEN TO USE IT: Use this for any application deployed to more than one environment (e.g., local development, staging, and production). It's ideal for managing database connection strings, external API endpoints, log levels, port numbers, and feature flags that behave differently in dev versus prod.

WHEN NOT TO USE IT: Do not use configuration files to store secrets like API keys, passwords, or private certificates, as these files are typically committed to version control. A better practice is to load secrets directly from environment variables or a dedicated secrets management service (like AWS Secrets Manager or HashiCorp Vault), which node-config can also integrate with.

ONE CANONICAL EXAMPLE: A Node.js app has a config/default.json with a local database setting: { "Customer": { "dbConfig": { "host": "localhost", "port": 5984 } } }. For production, a file config/production.json overrides the host: { "Customer": { "dbConfig": { "host": "prod-db-server" } } }. When the app runs with NODE_ENV=production, config.get('Customer.dbConfig.host') returns "prod-db-server", but config.get('Customer.dbConfig.port') still returns 5984 from the default file.

Read the original → github.com

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.