Environment Variables for Secrets
What You'll Learn
You'll learn how to use .env files and environment variables to keep sensitive credentials like API keys secure and out of your codebase.
The Problem with Hardcoded Secrets
Imagine leaving your house key under the doormat, then posting a photo of your doormat on social media. That's essentially what happens when you hardcode API keys directly in your source code:
# ❌ NEVER do this!
api_key = "sk-proj-abc123xyz789"
When this code gets committed to version control (like Git), your secret is now permanently in the repository's history—even if you delete it later. Anyone with access to the repo can find and abuse your credentials.
The Solution: Environment Variables
Environment variables are dynamic values stored outside your code, in your system's environment. They act like a secure lockbox that your application can read from at runtime, without exposing secrets in the source code itself.
Using .env Files
A .env file stores your secrets locally in a simple format:
OPENAI_API_KEY=sk-proj-abc123xyz789
ANTHROPIC_API_KEY=sk-ant-xyz456def789
DATABASE_URL=postgresql://user:pass@host/db
Critical: Add .env to your .gitignore file immediately so it never gets committed.
Reading Environment Variables in Code
import os
from dotenv import load_dotenv
# Load variables from .env file
load_dotenv()
# Access secrets safely
api_key = os.getenv("OPENAI_API_KEY")
In production, you'll set environment variables directly in your deployment platform (AWS, Azure, Vercel, etc.) rather than using a .env file.
The Analogy
Think of environment variables as a valet key for your car: it starts the engine (runs your app) but doesn't open the trunk or glove box (your repo). The real key (secret) stays with you, not in the car manual everyone can read.
Key Takeaway: Always store API keys and secrets in environment variables or .env files (excluded from version control), never in your source code—this prevents accidental exposure and makes credential management across environments seamless.