Lesson 35 +10 XP

Environment Variables with dotenv

Managing Configuration with .env

Never hardcode database URIs, API secrets, or port numbers in source code. Use environment variables managed by the dotenv package.

Creating a .env File

# .env file (Add to .gitignore!)
PORT=5000
NODE_ENV=development
MONGODB_URL=mongodb+srv://admin:pass123@cluster.mongodb.net/mydb
JWT_SECRET=super_secret_jwt_key_99

Loading Environment Variables in Server Code

// Load dotenv at the VERY START of your application entry point
require("dotenv").config();

const express = require("express");
const app = express();

const PORT = process.env.PORT || 3000;
const DB_URL = process.env.MONGODB_URL;

console.log("Running in environment:", process.env.NODE_ENV);

[!CAUTION] Always add .env to your .gitignore file so confidential database credentials are never committed to public version control repositories!

TL;DR

  • Store secrets in .env files.
  • Load variables into process.env using require('dotenv').config().
  • Add .env to .gitignore.