Environment with dotenv
Load configuration from a .env file into process.env.
Syntax
require('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
- Create a
.envfile withKEY=valuelines. - Add
.envto.gitignore. - 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
// .env file:
// PORT=8080
// API_KEY=secret123
require('dotenv').config();
console.log('Port:', process.env.PORT); // 8080
console.log('Key:', process.env.API_KEY); // secret123When 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`.
// 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.
# .env -- NEVER commit this file
PORT=4000
NODE_ENV=development
DB_URL=postgres://user:pass@localhost:5432/mydb
JWT_SECRET=supersecretkey123Validate env vars after loading
Loads the `.env` file and then validates that required variables are present before the app continues.
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