Node.js: Code Outside the Browser / Environment Variables & Configurations

Managing configuration safely using the dotenv package

πŸ“₯ 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 need process.env values, those files will see undefined. Always load it first.

  • Wrong working directory β€” dotenv looks for .env relative to where you run the command, not where the file lives. Running node src/index.js from the project root still expects .env at the root.

  • Everything is a string β€” process.env.PORT is "3000", not the number 3000. 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 .env file early, instead of silently getting undefined values later.