Securing Secrets in My Backend App with .env Files
Before pushing my full backend application to GitHub, I paused. I realized there was a risk I might expose sensitive credentials—like my Azure connection strings, storage keys, or app secrets—embedded somewhere in the code.
That’s when I took a step back and implemented environment-based configuration using .env
files and the python-dotenv package to manage secrets securely.
🔐 Why You Should Never Push Secrets to GitHub
- Exposed credentials can be exploited instantly
- You may violate platform security policies (Azure, AWS, GCP)
- You risk data leaks, billing abuse, or losing access to your own services
✅ How I Secured My App with a .env File
Step 1: Create a .env File
# .env
AZURE_STORAGE_CONNECTION_STRING="DefaultEndpointsProtocol=https;AccountName=***;AccountKey=***;EndpointSuffix=core.windows.net"
CONTAINER_NAME="test"
APPLICATIONINSIGHTS_CONNECTION_STRING="InstrumentationKey=XXX;IngestionEndpoint=..."
SECRET_KEY="If7e29=="
# Optional DB config example
DB_HOST=localhost
DB_USER=mysecretusername
DB_PASSWORD=mysecretdinosaurpassword
DB_NAME=mysecretdatabase
Step 2: Install python-dotenv
pip install python-dotenv
Step 3: Load Environment Variables in Your Python Code
from dotenv import load_dotenv
import os
load_dotenv() # Load variables from .env into environment
connection_string = os.getenv("AZURE_STORAGE_CONNECTION_STRING")
container_name = os.getenv("CONTAINER_NAME")
secret_key = os.getenv("SECRET_KEY")
# Example: Create a database connection string
db_host = os.getenv("DB_HOST")
db_user = os.getenv("DB_USER")
db_password = os.getenv("DB_PASSWORD")
db_name = os.getenv("DB_NAME")
db_url = f"mysql+pymysql://{db_user}:{db_password}@{db_host}/{db_name}"
Step 4: Add .env to Your .gitignore
# .gitignore
.env
This ensures your .env file stays local and is never committed to version control.
📁 Recommended Naming Conventions
If you're managing multiple environments, you can keep things organized using descriptive names:
| Purpose | Example |
|---|---|
| Default / Local Dev | .env |
| Development | .env.development |
| Testing | .env.testing |
| Staging | .env.staging |
| Production | .env.production |
| App-Specific | .env.analytics.dev, .env.api.prod |
📌 TL;DR Summary
- Always hide your secrets using environment variables
- Use
python-dotenvto load variables in Python projects - Never push your
.envfile to GitHub - Use naming conventions to manage multiple environments
💬 Final Thoughts
Security isn't a feature—it's a habit. This step may not be flashy, but it’s a critical part of building a product that’s secure and ready for growth.
I can now confidently push my backend repo to GitHub without exposing private credentials—ready for open-source collaboration or deployment automation down the road.
Want help setting up your environment securely? Let’s connect.