Course contentsShow
← JavaScript
Lesson 1512 of 2,72333. JavaScript in Node.jsFree lesson

Using .env Files with dotenv

Load environment variables from a .env file using the dotenv package for local development.

Using .env Files with dotenv

You'll learn how to manage environment variables in local development by loading them from a .env file using the dotenv package.

Why .env Files?

In the previous lesson, you learned to set environment variables in your shell before running your Node.js app. But typing export API_KEY=abc123 every time—or maintaining long shell scripts—gets tedious fast, especially with multiple variables.

The .env file is a simple text file in your project root that lists environment variables in KEY=VALUE format. The dotenv package reads this file at runtime and injects those variables into process.env, making local development much smoother.

How It Works

Think of .env as your personal configuration file that never gets committed to version control (you add it to .gitignore). It's like having a private settings panel that dotenv automatically loads when your app starts.

Installing dotenv:

npm install dotenv

Create a .env file in your project root:

API_KEY=my-secret-key-123
DATABASE_URL=mongodb://localhost:27017/myapp
PORT=3000

Load it at the top of your entry file (e.g., index.js):

require('dotenv').config();

console.log(process.env.API_KEY);        // "my-secret-key-123"
console.log(process.env.DATABASE_URL);   // "mongodb://localhost:27017/myapp"
console.log(process.env.PORT);           // "3000"

Calling config() reads the .env file and merges those values into process.env. Now your app can access them just like any environment variable.

Important: Always add .env to your .gitignore so secrets stay local. Commit a .env.example file instead with placeholder values to show teammates what variables are needed.

Key Takeaway: The dotenv package loads environment variables from a .env file into process.env, simplifying local development configuration without exposing secrets in your codebase.