3. Environment Variables & Keeping Secrets Safe
Environment Variables
Your code will need passwords, API keys, and database URLs. If you hardcode these into your source code and push to GitHub, anyone on the internet can steal them. Environment variables solve this problem.
The Problem: Hardcoded Secrets
// NEVER DO THIS — Your password is now on the internet! const databasePassword = "MySecretPassword123"; const apiKey = "sk_live_abc123xyz";
If you push this to GitHub, bots will scan your repository within minutes and steal your keys. Hackers can then access your database or run up massive bills on your payment API.
The Solution: Environment Variables
An environment variable is a value stored in the operating system, not in your code. Your code reads it at runtime. Different environments (your laptop vs production server) can have different values.
Create a file called .env in your project folder:
# .env file — NEVER commit this to Git! PORT=3000 DATABASE_URL=postgresql://localhost/mydb JWT_SECRET=your-super-secret-key-here API_KEY=sk_test_12345
.env to your .gitignore file immediately. This prevents Git from tracking it.Reading Environment Variables in Node.js
Install the dotenv package: npm install dotenv
// Load environment variables from .env file require('dotenv').config(); // Now read them using process.env const port = process.env.PORT || 3000; const dbUrl = process.env.DATABASE_URL; const jwtSecret = process.env.JWT_SECRET; console.log(`Server will run on port: ${port}`); // Always check that required secrets exist! if (!jwtSecret) { console.error("FATAL: JWT_SECRET environment variable is missing!"); process.exit(1); // Stop the server } console.log("All environment variables loaded successfully");
Reading Environment Variables in Python
Install python-dotenv: pip install python-dotenv
from dotenv import load_dotenv import os # Load environment variables from .env file load_dotenv() # Now read them using os.getenv() port = os.getenv('PORT', 8000) db_url = os.getenv('DATABASE_URL') jwt_secret = os.getenv('JWT_SECRET') print(f"Server will run on port: {port}") # Always check that required secrets exist! if not jwt_secret: print("FATAL: JWT_SECRET environment variable is missing!") exit(1) print("All environment variables loaded successfully")
The .env.example File
You can't commit your real .env file. But you SHOULD commit a template so other developers know what variables they need. Create .env.example:
# .env.example — COMMIT this file to Git # Copy this file to .env and fill in your real values PORT=3000 DATABASE_URL=postgresql://USER:PASSWORD@HOST:PORT/DATABASE JWT_SECRET=replace-this-with-a-long-random-string API_KEY=your-api-key-here
Now when a new developer clones your project, they copy .env.example to .env and fill in their own values.
Knowledge Check
Ready to test your understanding of 3. Environment Variables & Keeping Secrets Safe?