Configuration and dotenv
Keep secrets and settings in environment variables. Node 20.6+ reads a .env file with --env-file, so dotenv is optional. Provide defaults and validate on start.
Example
const cfg = {
port: Number(process.env.PORT ?? 3000),
debug: process.env.DEBUG === '1',
};
if (Number.isNaN(cfg.port)) throw new Error('PORT must be a number');
console.log(cfg);
// node --env-file=.env app.jsResult
{ port: 3000, debug: false }Exercise
Load a .env file.
node =.env app.js
Quiz Test
These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.