Environment with dotenv

Load configuration from a .env file into process.env.

Syntaxrequire('dotenv').config();

The popular dotenv package reads a .env file and loads its values into process.env. It keeps secrets and settings out of your code.

How to use it

  1. Create a .env file with KEY=value lines.
  2. Add .env to .gitignore.
  3. Load it early in your app.

Modern Node can also load a .env file with the built-in --env-file flag, no package needed.

Example

Example · javascript
// .env file:
//   PORT=8080
//   API_KEY=secret123

require('dotenv').config();

console.log('Port:', process.env.PORT);       // 8080
console.log('Key:', process.env.API_KEY);     // secret123

When to use it

  • A developer stores database credentials in a `.env` file that is `.gitignore`d, loaded by `dotenv` at startup, and never committed to source control.
  • A multi-environment setup uses `.env.development` and `.env.production` files with `dotenv` to configure the app for each deploy target.
  • A Docker-based service uses a `.env` file via `docker-compose --env-file` so the same `dotenv.config()` call reads secrets in local dev and in containers.

More examples

Basic dotenv setup

Calls `dotenv.config()` once at app startup to load `.env` variables into `process.env`.

Example · js
// At the very top of your entry file:
require('dotenv').config();

// Now process.env has values from .env
console.log(process.env.PORT);      // '4000'
console.log(process.env.DB_URL);    // 'postgres://...'

Sample .env file

A typical `.env` file with key=value pairs -- add `.env` to `.gitignore` immediately.

Example · bash
# .env  -- NEVER commit this file
PORT=4000
NODE_ENV=development
DB_URL=postgres://user:pass@localhost:5432/mydb
JWT_SECRET=supersecretkey123

Validate env vars after loading

Loads the `.env` file and then validates that required variables are present before the app continues.

Example · js
require('dotenv').config();

const { PORT, DB_URL, JWT_SECRET } = process.env;
if (!DB_URL || !JWT_SECRET) {
  console.error('Missing required env vars');
  process.exit(1);
}

console.log(`Starting on port ${PORT || 3000}`);

Discussion

  • Be the first to comment on this lesson.