.env File Security Best Practices: Keep Your Secrets Safe
Should you commit .env files? How to secure environment variables? Complete guide to .env file security for developers.
.env File Security Best Practices: Keep Your Secrets Safe
The .env file is where developers store sensitive configuration. Database passwords, API keys, OAuth tokensβthey all live there. Yet it's one of the most frequently leaked files in web applications.
Should You Commit .env Files?
The answer is simple: Never commit .env files to version control.
Even if you add it to .gitignore, mistakes happen. Developers accidentally commit the wrong file. CI/CD systems expose variables. The risk is too high.
Common .env Security Mistakes
Mistake #1: Committing .env to Git
git add .env # π¨ DO NOT DO THIS
Mistake #2: Hardcoding Secrets in Docker
ENV API_KEY="sk_prod_secret" # π¨ Visible in image
Mistake #3: Logging Environment Variables
console.log(process.env); // π¨ May expose secrets in logs
The Right Way to Manage .env Files
Step 1: Create .env.example
Create a template with placeholder values:
# .env.example
DATABASE_URL=postgres://user:password@localhost:5432/db
API_KEY=your_api_key_here
STRIPE_KEY=sk_test_xyz
JWT_SECRET=your_secret_here
Step 2: Add .env to .gitignore
# .gitignore
.env
.env.local
.env.*.local
Step 3: Use a Secrets Manager
For production, never use .env files. Use:
- XtraSecurity
- AWS Secrets Manager
- HashiCorp Vault
- Azure Key Vault
Step 4: Rotate Secrets Regularly
Change all secrets every:
- 30 days for database credentials
- 7 days for API keys
- Immediately if compromised
Implementation Examples
Development Setup
# 1. Create .env.local with your secrets
Docker Setup
FROM node:18
WORKDIR /app
COPY . .
RUN npm install
# Don't embed secrets in image
CMD ["npm", "start"]
Docker Compose with XtraSecurity
version: '3'
services:
api:
image: myapp:latest
environment:
DATABASE_URL: ${DATABASE_URL}
API_KEY: ${API_KEY}
Red Flags in .env Files
Never include in .env:
- β Production database passwords
- β API keys for paid services
- β OAuth tokens
- β JWT secrets
- β SSH keys
- β Encryption keys
Securing .env Files
Use file permissions:
chmod 600 .env # Only user can read
Conclusion
.env files are critical infrastructure. Treat them with the same security as production databases.
About the Author
OM Salunke is a security engineer with expertise in DevOps, cloud infrastructure, and secrets management. He has helped enterprise teams secure their infrastructure on AWS, Google Cloud, and Azure.