Node.js
Summary - Configuration
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.
Exercise 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.
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
-
What pieces does the configuration skeleton combine?
dotenv + process.env + config
- Only require
- Only console.log
- Only throw
- dotenv, process.env and config object
Show answer
dotenv, process.env and config object — dotenv + process.env + config combine.
-
Match each tool to its role
- require("dotenv").config()
- Loads .env
- process.env.PORT
- Reads the variable
- || 3000
- Default value
- config object
- Gathers configuration
Next lesson: Integration tests