Node.js ยท Chapter 29 of 43

Environment Variables

Environment variables store configuration outside your code, like database URLs, API keys, and secrets. This keeps sensitive data out of source control.

The `dotenv` package lets you load variables from a `.env` file into `process.env` during development.

Using process.env

Node.js exposes environment variables through the global `process.env` object as strings.

Loading a .env file

Install `dotenv`, create a `.env` file, and call `require('dotenv').config()` at the top of your entry file.

Example 1 (javascript)
// .env file
// PORT=4000
// DATABASE_URL=postgres://...

require('dotenv').config();
console.log(process.env.PORT);
Output
4000

dotenv loads key-value pairs from .env into process.env.

Example 2 (javascript)
const port = process.env.PORT || 3000;
app.listen(port, () => console.log('Running on ' + port));
Output
Running on 4000

Falling back to a default port keeps the app working even without a .env file.

Key points

  • process.env exposes environment variables as strings.
  • dotenv loads variables from a .env file.
  • Never commit .env files containing secrets to version control.
  • Use fallback defaults for optional environment variables.
๐Ÿ’ก Note: Add `.env` to your `.gitignore` to avoid leaking secrets.

๐Ÿ“ Quick Quiz

1. Where does Node.js expose environment variables?

2. Which package commonly loads .env files?

3. Why shouldn't .env files be committed to git?