Node.js
Config hierarchy
Learn the config file hierarchy.
Config hierarchy
In big projects, configuration is not kept in a single .env. Separate files are used for different environments (.env.development, .env.production) and a defaults file (.env.defaults). This builds a config hierarchy.
Example: .env.defaults holds defaults shared by everyone, .env.development holds values specific to development. Load order: defaults first, then the environment file. This way the environment file overrides the defaults. The code gathers configuration into a config object: const config = { port: process.env.PORT, db: process.env.DATABASE_URL };. This object is used everywhere in the app. The config object lets you manage configuration from a single place.
The config object
Gathering configuration into a single config object is good practice. This object is used everywhere in the app; instead of accessing process.env directly, you write config.port.
Example: const config = { port: process.env.PORT || 3000, dbUrl: process.env.DATABASE_URL, nodeEnv: process.env.NODE_ENV };. This object is defined once at startup and exported to other files. Advantages: configuration in one place, consistent names, easy testing. Direct access to process.env gets scattered across files; the config object centralizes it. In production you export config as a module and import it everywhere.
Exercise Create a config object
Enable dotenv. Create a config object with const config = { port: process.env.PORT || 3000, nodeEnv: process.env.NODE_ENV || "development" }. Print config.port with console.log.
Show example solution
require("dotenv").config();
const config = {
port: process.env.PORT || 3000,
nodeEnv: process.env.NODE_ENV || "development"
};
console.log(config.port);
Test yourself
-
Match each file to its role
- .env.defaults
- Default values
- .env.development
- Development environment
- .env.production
- Production environment
- config object
- Gathers configuration
-
Why use a config object?
const config = { port: process.env.PORT }
- For more colorful console
- For faster network
- For less memory
- To gather configuration in one place
Show answer
To gather configuration in one place — A config object centralizes configuration.
-
Complete the config object line
const config = { port: process.____.PORT || 3000 };
Show answer
const config = { port: process.env.PORT || 3000 };
Next lesson: Validation