← Back to Node.js Course | Chapter 9: Database Integration | Lesson 3 of 7

Environment variables (.env)

A .env file keeps settings and secrets out of your code and out of git.
Syntax
javascript
# .env
KEY=value

// app.js
require('dotenv').config();
const value = process.env.KEY;

Environment variables (.env)

The dotenv package loads KEY=value lines from .env into process.env at start-up. Node 20.6 and later can load it with node --env-file=.env. Add .env to .gitignore and commit a .env.example listing names only.

Note: Never commit .env with real secrets.

Example: Environment variables (.env)

javascript
function parseEnv(text) {
  const out = {};
  for (const line of text.split("\n")) {
    const m = line.match(/^\s*([A-Z_]+)\s*=\s*(.*)\s*$/);
    if (m) out[m[1]] = m[2];
  }
  return out;
}
const env = parseEnv("PORT=3000\nDB_HOST=localhost\n");
console.log(env, typeof env.PORT, Number(env.PORT) + 1);

// Output:
// { PORT: '3000', DB_HOST: 'localhost' } string 3001

⚠️ Run this in your own terminal or Node.js environment.

Related Topics
Common Mistakes
  1. Committing secrets
  2. Forgetting to load dotenv before reading variables
  3. Assuming values are numbers
Chapter Summary
  • .env holds configuration
  • dotenv or --env-file loads it
  • Values are strings
  • Keep it out of git
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.