Use Environment Variables for Configuration
Table of Contents
- Introduction
- Why Use Environment Variables?
- How to Set Environment Variables
- Examples in Different Frameworks
- Best Practices
- Common Pitfalls
- Developer Checklist
- Conclusion
Introduction
In modern application development, configuration plays a critical role. Instead of hardcoding sensitive or environment-specific values inside your code, it is a best practice to use environment variables. This allows flexibility, security, and easier deployment across development, testing, and production environments.
Why Use Environment Variables?
- Keep sensitive data (like API keys, DB credentials) out of source code.
- Enable easy switching between environments (dev, staging, prod).
- Avoid configuration drift and deployment issues.
How to Set Environment Variables
Unix/Linux/macOS
# Temporary for session export DB_URI=mysql://user:password@localhost:3306/mydb # Add to ~/.bashrc or ~/.zshrc for persistence export API_KEY=yourapikeyhere
Windows (PowerShell)
# Set for current session
$env:DB_URI = "mysql://user:password@localhost:3306/mydb"
# Permanently set (requires restart of shell)
[System.Environment]::SetEnvironmentVariable("API_KEY", "yourapikeyhere", "User").env Files (Local Development)
# .env file DB_URI=mysql://user:password@localhost:3306/mydb API_KEY=yourapikeyhere
Many frameworks (Express, Laravel, Django, Rails, etc.) can load variables from a .env file automatically during development.
Docker
# Dockerfile ENV API_KEY=yourapikeyhere # docker run with env var docker run -e DB_URI=mysql://user:pass@db:3306/mydb myapp
Kubernetes
# deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: myapp
spec:
template:
spec:
containers:
- name: myapp
image: myapp:latest
env:
- name: DB_URI
valueFrom:
secretKeyRef:
name: myapp-secrets
key: db-uriExamples in Different Frameworks
ASP.NET
// Program.cs
var builder = WebApplication.CreateBuilder(args);
// Read environment variable
string connString = Environment.GetEnvironmentVariable("DB_CONNECTION") ?? "";
builder.Services.AddDbContext<MyDbContext>(options =>
options.UseSqlServer(connString));
var app = builder.Build();
app.MapGet("/", () => "ASP.NET with ENV vars");
app.Run();Spring Boot
// application.properties
spring.datasource.url=${DB_URL}
spring.datasource.username=${DB_USER}
spring.datasource.password=${DB_PASS}Express.js
// server.js
const express = require('express');
const app = express();
const PORT = process.env.PORT || 3000;
const DB_URI = process.env.DB_URI;
app.get('/', (req, res) => {
res.send('Express running with ENV vars');
});
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));Next.js
// next.config.js
module.exports = {
env: {
API_URL: process.env.API_URL,
},
};
// pages/index.js
export default function Home() {
return <div>API URL: {process.env.API_URL}</div>;
}Flask
# app.py
import os
from flask import Flask
app = Flask(__name__)
DB_URI = os.getenv("DB_URI")
@app.route("/")
def home():
return f"Flask running with DB: {DB_URI}"Laravel
// .env
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=mydb
DB_USERNAME=root
DB_PASSWORD=secret
// config/database.php
'mysql' => [
'driver' => 'mysql',
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
],Best Practices
- Never commit
.envfiles to version control. - Use secrets managers (AWS Secrets Manager, Vault, Kubernetes Secrets) for sensitive data.
- Document required environment variables for onboarding developers.
- Use defaults where possible but fail fast if critical variables are missing.
Common Pitfalls
- Accidentally exposing environment variables in logs or error messages.
- Forgetting to reload the application after changing environment variables.
- Mixing configuration logic into code instead of keeping it externalized.
- Using environment variables for large configuration data instead of keeping them small and simple.
Developer Checklist
| ✔️ Do | ❌ Don't |
|---|---|
| Keep API keys, secrets, and DB creds in env vars | Hardcode sensitive info in code |
| Use .env only for local dev | Commit .env files to Git |
| Use Kubernetes Secrets / AWS Secrets Manager in production | Store secrets directly in Dockerfiles |
| Validate required env vars at app startup | Assume they are always present |
Conclusion
Environment variables are essential for secure, flexible, and scalable application configuration. Without them, sensitive information may leak into version control, deployments may become rigid, and scaling across environments would be error-prone.
By adopting environment variables across frameworks like ASP.NET, Spring Boot, Express, Next.js, Flask, and Laravel, you ensure that your applications remain secure, portable, and production-ready.