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

Creating .env files

πŸ“‚ The .env File

A .env file contains your environment variables, one per line:

PORT=3000
DB_PASSWORD=mySecret123
API_KEY=abc123xyz
  • Place it in your project root β€” the same level as your package.json and main JS files.

  • No quotes needed around values, no spaces around the = sign, and no semicolons at the end of a line.

  • Comments start with #:

# Database config
DB_PASSWORD=mySecret123

πŸ’‘ Variants of .env Files

  • .env β€” the default file, loaded in all environments unless a more specific one overrides it.

  • .env.local β€” developer-specific overrides. Ignored in version control, so it's ideal for machine-specific settings that shouldn't apply to teammates.

  • .env.development β€” loaded when NODE_ENV=development.

  • .env.production β€” loaded when NODE_ENV=production.

  • .env.test β€” loaded when NODE_ENV=test, typically during automated test runs.

  • .env.example β€” documents which env vars the project needs, with placeholder values instead of real secrets. Safe to commit, and helpful for onboarding other developers.

βš™οΈ Tools like Vite and Next.js load these environment-specific files automatically based on NODE_ENV. Plain Node with dotenv doesn't do this out of the box β€” you'd need to point .config() at the right file yourself (see below).


πŸ”„ Loading .env in Your Code

Install the dotenv package:

npm install dotenv

Load it as early as possible in your entry file:

require('dotenv').config();

console.log(process.env.PORT);        // 3000
console.log(process.env.DB_PASSWORD); // mySecret123

Loading a Specific .env File

By default, dotenv only reads .env. To load a different file (like .env.production), pass a path option:

require('dotenv').config({ path: '.env.production' });

A common pattern is to pick the file based on NODE_ENV:

require('dotenv').config({
  path: `.env.${process.env.NODE_ENV || 'development'}`
});

πŸ’‘ Node 20.6+ can skip dotenv entirely for the default file, using node --env-file=.env app.js.


πŸ›‘οΈ Pro Tips

  • Never commit .env, .env.local, or any file with real secrets β€” add them to .gitignore before your first commit.

  • Do commit .env.example with placeholder values, so collaborators know exactly what to fill in.

  • If a secret ever does get committed, rotate it (change the actual password/key) β€” removing it from a later commit doesn't erase it from Git history.