Environment Variables: Managing Configuration Without Hard-Coding
Hard-coded API keys in your code are a security incident waiting to happen. Here's the right way to manage configuration across environments.
In 2024, GitHub reported removing 1.3 million leaked secrets from public repositories. API keys, database passwords, and private keys committed to git, sometimes minutes after being created. The solution is simple and should be set up on day one of every project.
The .env Setup
Create .env.example with all your variable names and placeholder values — this gets committed and shows other developers what's needed. Create .env.local with real values — this never gets committed. Add .env.local to .gitignore immediately. This workflow means new team members know what variables exist without seeing real secrets.
Naming Conventions
Use SCREAMING_SNAKE_CASE (all caps, underscores). Group related variables with prefixes: DATABASE_URL, DATABASE_MAX_CONNECTIONS for database settings. APP_SECRET, APP_PORT for application settings. In Next.js, prefix browser-exposed variables with NEXT_PUBLIC_ — anything without the prefix is server-only. This naming convention prevents accidentally exposing server secrets to client-side code.
Validating on Startup
Apps that silently fail because of missing environment variables are painful to debug. Add startup validation: check that required variables are set and throw a clear error if they're missing. In Node.js: throw new Error('MISSING ENV VAR: DATABASE_URL is required'). Fail loudly at startup rather than mysteriously at runtime when the variable is first used.
If You've Already Committed a Secret
Rotate the key immediately — don't wait. The credential is compromised the moment it's in git, even if you haven't pushed publicly. After rotating: remove it from the latest commit, rewrite history with git-filter-repo to remove it from all commits (more thorough than git filter-branch), and force push. Then audit whether the key was used by anyone else.
Pre-commit hook
Gitleaks (open-source) can run as a pre-commit hook to scan staged files for secrets before they're committed. Add it to your project's setup docs so every developer has the protection. A 50ms check on every commit is worth it.
Frequently Asked Questions
What are environment variables?+
Why should I never commit API keys to git?+
What's the difference between .env and .env.local?+
How do I manage environment variables in production?+
🔧 Free Tools Used in This Guide
FreeToolKit Team
FreeToolKit Team
We build free browser-based tools and write practical guides that skip the fluff.
Tags: