π₯ Managing Configuration with the dotenv Package
Node.js doesn't read .env files automatically β that's what the dotenv package is for. It reads the file and copies its key-value pairs into process.env.
π¦ Step 1: Install dotenv
npm install dotenvπ§ͺ Step 2: Load the .env File in Your Code
Import it only once, ideally at the very top of your root file (like index.js), before anything else runs:
require('dotenv').config();
const port = process.env.PORT;
const dbPass = process.env.DB_PASSWORD;
console.log(`Server running on port: ${port}`);
console.log(`Database password is: ${dbPass}`);π Sample .env
PORT=3000
DB_PASSWORD=superSecret456π¨οΈ Output
Server running on port: 3000
Database password is: superSecret456β οΈ Common Gotchas
Loading it too late β if
.config()runs after other files that needprocess.envvalues, those files will seeundefined. Always load it first.Wrong working directory β
dotenvlooks for.envrelative to where you run the command, not where the file lives. Runningnode src/index.jsfrom the project root still expects.envat the root.Everything is a string β
process.env.PORTis"3000", not the number3000. Convert manually when needed:Number(process.env.PORT).
π Checking If It Loaded Correctly
.config() returns an object you can inspect for errors:
const result = require('dotenv').config();
if (result.error) {
console.error('β Failed to load .env file:', result.error);
} else {
console.log('β
.env loaded successfully');
}Useful for catching a missing or misplaced
.envfile early, instead of silently gettingundefinedvalues later.