Authentication and AuthorizationLesson 4.5
How to use environment variables to protect secrets in Express
dotenv package, .env file, process.env, .gitignore env file, JWT_SECRET, DATABASE_URL, NODE_ENV, env validation on startup
Environment Variables for Configuration
Hardcoding secrets (JWT secrets, API keys, DB passwords) into source code is a security vulnerability. Environment variables keep secrets out of version control.
npm install dotenv.env file (never commit this)
PORT=3000
JWT_SECRET=your_super_secret_key_min_32_chars
NODE_ENV=development
DB_URL=postgresql://user:pass@localhost:5432/mydb.gitignore
.env
.env.local
node_modules/app.js — load as first line
require('dotenv').config(); // must be before any other require that uses process.env
const express = require('express');
const app = express();
const PORT = process.env.PORT || 3000;
const JWT_SECRET = process.env.JWT_SECRET;
// Validate required env vars on startup
if (!JWT_SECRET) {
console.error('FATAL: JWT_SECRET is not set');
process.exit(1);
}
app.listen(PORT, () => console.log(`Running on port ${PORT}`));Fail fast on startup if required env vars are missing — crashing immediately is safer than running with undefined secrets. Provide a .env.example file with dummy values in your repo so new developers know what variables to set.
