Summary - Configuration
- Node.js course
- Advanced
- Lesson 72/83
- 5 min
Combine dotenv, env and validation to write a config system.
Summary - Configuration
In this group you learned the core tools of configuration in Node.js: loading .env with dotenv, reading variables with process.env, centralizing configuration with a config object, catching errors early with validation, and managing secrets safely.
Now you will combine these into a small configuration skeleton. The skeleton will enable dotenv, read the port, give a default, and gather it into a config object. This mini task shows how the configuration tools combine.
Configuration design
A production configuration skeleton is this: loading with require("dotenv").config(), reading with process.env.PORT || 3000, gathering with const config = { ... }. Validation can also be added.
Flow: require("dotenv").config(); const config = { port: process.env.PORT || 3000, nodeEnv: process.env.NODE_ENV || "development" }; if (!config.port) throw new Error("PORT required");. This skeleton loads dotenv, reads the port, gives a default, gathers it into a config object, and validates. In production, secrets are also added to the config object but never logged. Separate files for different environments can be added on top of this skeleton.
Practice Build the configuration skeleton
Enable dotenv with require("dotenv").config(). 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 and 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 What pieces does the configuration skeleton combine?
dotenv + process.env + config- Only require
- Only console.log
- Only throw
- dotenv, process.env and config object Correct answer
Explanation: dotenv + process.env + config combine.
2 Match each tool to its role
| Term | Meaning |
|---|---|
require("dotenv").config() |
Loads .env |
process.env.PORT |
Reads the variable |
|| 3000 |
Default value |
config object |
Gathers configuration |