Committing a secret to Git is one of those mistakes that feels harmless right up until it isn’t. An API key, a database password, or a .env file slips into a commit, gets pushed, and now it lives in your repository history forever — even if you delete it in the next commit. Here is a quick, practical habit to keep secrets out of Git for good.
Start every project with a .gitignore
Before your first commit, add a .gitignore that excludes the usual culprits:
.env
.env.local
*.pem
*.key
secrets.json
node_modules/
The single most valuable line there is .env. Keep your real configuration in a git-ignored .env file, and commit a .env.example with the keys but not the values, so teammates know what to set without ever seeing your credentials.
If a secret already slipped in
Deleting it in a new commit is not enough — it is still in history. Rotate the exposed credential immediately (assume it is compromised), then scrub it from history with a tool like git filter-repo or BFG. Rotation is the part people skip, and it is the part that actually protects you.
Add a safety net
Humans forget, so let a tool watch your back. A pre-commit hook using something like gitleaks or git-secrets scans staged changes and blocks the commit if it spots something that looks like a key. It takes five minutes to set up and has saved countless developers from a very bad afternoon.
Keeping secrets out of Git comes down to three habits: ignore them by default, rotate anything that leaks, and let a scanner catch what you miss. Build those in early and you will never have to write that awkward “please rotate the key I just pushed” message.

