Ignoring .env and Secret Files in Git
Securely ignore .env files in git to protect API keys and secrets. Covers .env.local, .env.production, and framework-specific environment file handling.
Detailed Explanation
Environment files are one of the most security-critical patterns in any .gitignore. A single committed .env file containing database credentials or API keys can lead to a data breach, especially in public repositories.
What are .env files?
The .env convention (popularized by the dotenv library) stores configuration as key-value pairs:
DATABASE_URL=postgres://user:password@host:5432/db
STRIPE_SECRET_KEY=sk_live_abc123
JWT_SECRET=my-super-secret-key
These files are loaded into process.env at runtime. They allow different environments (development, staging, production) to use different configurations without code changes.
Recommended ignore patterns:
.env
.env.local
.env.*.local
.env.development.local
.env.production.local
What to commit vs. ignore:
Many frameworks (Next.js, CRA, Vite, Laravel) support a hierarchy of env files. A common convention:
- Commit
.env.example— A template with all required variable names but placeholder values. This documents what environment variables the app needs without exposing real secrets. - Commit
.env.development— Non-sensitive development defaults (e.g.,API_URL=http://localhost:3000). - Ignore
.env.local— Personal overrides that may contain real API keys for local testing. - Ignore
.env.production— Production secrets should come from your hosting platform's environment variable configuration, never from a committed file.
What to do if you accidentally committed secrets:
- Immediately rotate the exposed credentials (new API key, new database password).
- Remove the file:
git rm --cached .env - Add it to
.gitignoreand commit. - Consider using
git filter-branchor BFG Repo-Cleaner to scrub the secret from git history, because it remains accessible in old commits even after removal.
Prevention: Use tools like git-secrets or pre-commit hooks that scan for patterns resembling API keys before allowing a commit to go through.
Use Case
A startup discovered their AWS credentials were exposed in a public GitHub repository and needs to set up proper .env handling to prevent future secret leaks.