Script Valley
Web Security Fundamentals for Developers
Secrets Management, Dependencies, and Security in CI/CDLesson 6.1

How secrets leak and how to manage them with environment variables

secret types, git history leaks, .env files, dotenv library, .gitignore best practices, secret rotation, 12-factor app config, never hardcoding secrets

Secrets Management

Secret leakage paths diagram

A secret is any value that grants access: API keys, database passwords, JWT secrets, OAuth client secrets, TLS private keys. Once a secret is in a git repository, even a private one, treat it as compromised. GitHub bots scan public repos in under a minute.

The Right Pattern: Environment Variables

// .env file — never commit this
JWT_SECRET=a_long_random_string_here_at_least_32_chars
DB_PASSWORD=another_secret_value
STRIPE_SECRET_KEY=sk_live_...

// .gitignore — always include these
.env
.env.local
.env.production
*.pem
*.key

// Load in application
require('dotenv').config(); // Call once, at app entry point
const secret = process.env.JWT_SECRET;
if (!secret) throw new Error('JWT_SECRET not set — refusing to start');

Validating Required Secrets at Startup

const required = ['JWT_SECRET', 'DB_PASSWORD', 'STRIPE_SECRET_KEY'];
for (const key of required) {
  if (!process.env[key]) {
    throw new Error(`Missing required environment variable: ${key}`);
  }
}

If You Accidentally Commit a Secret

Immediately rotate the secret (issue a new one, revoke the old). Rewriting git history with git filter-branch or BFG Repo Cleaner removes the secret from the repo, but assume it was already seen. If it's a production credential (AWS key, payment key), assume it was used maliciously and investigate your logs.

Up next

How to use a secrets manager: Vault, AWS Secrets Manager, and dotenv-vault

Sign in to track progress