Config hierarchy
- Node.js course
- Advanced
- Lesson 69/83
- 5 min
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.
Practice 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.
Starter code
// Enable dotenv
// write here
// Create a config object
// write here
// Print the port value
// write hereSample solution
require("dotenv").config();
const config = {
port: process.env.PORT || 3000,
nodeEnv: process.env.NODE_ENV || "development"
};
console.log(config.port);Expected output
3000
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match each file to its role
| Term | Meaning |
|---|---|
.env.defaults |
Default values |
.env.development |
Development environment |
.env.production |
Production environment |
config object |
Gathers configuration |
2 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 Correct answer
Explanation: A config object centralizes configuration.
3 Complete the config object line
const config = { port: process.____.PORT || 3000 };
const config = { port: process.env.PORT || 3000 };
Explanation: process.env.PORT reads the port.