How do I stop committing secrets like API keys to Git, and remove one I already pushed?

0votes

Personal project on GitHub (public repo). A .env file with a Stripe secret key and a database password was committed and pushed three commits ago. The repo has one other collaborator.

Secrets should never appear in the repository history, and the exposed keys should be made useless to anyone who saw them.

The .env file is visible in the GitHub history. Adding it to .gitignore now hides it from new commits, but the old commits still expose the keys.

Question comments

Short clarifications and follow-ups about the question itself.

No comments yet.

1 Answer

Tai · AI answer

AI-generated answer

Revoke or rotate the exposed Stripe secret key and database password first. Removing a file from Git history cannot make a copied credential safe. Update the applications that use the replacement credentials and confirm the old ones no longer work. Review the providers’ access/activity logs for unexpected use.

Then stop tracking the file: add .env to .gitignore and use git rm --cached .env. That command removes it from the next commit while keeping the local file. Commit a safe .env.example containing variable names and dummy values, never working secrets.

Historical cleanup is a separate, coordinated step. Ask the collaborator to pause pushes, preserve legitimate work, and follow GitHub’s current sensitive-data removal procedure. It uses git-filter-repo and rewrites commit identities. Check all affected paths/renames and branches; simply editing the latest commit is insufficient when the secret was pushed earlier.

After any authorised rewrite, collaborators must clean or replace old clones so they do not push the old history back. Copies may remain in forks, caches or other people’s clones. Rotation remains the essential protection even when a repository’s visible history is cleaned.

To prevent recurrence, keep secrets in environment configuration or a secret manager, review staged diffs, and enable appropriate secret scanning/push protection. Do not paste the actual key or password into a public issue while requesting help.

The commands below only stop future tracking; they do not erase historical exposure.

Prepared with AI assistance by Tai. Official sources checked 17 October 2026; interfaces and provider policies may change.

  1. Rotate/revoke both exposed credentials and update their legitimate users.
  2. Remove .env from tracking while keeping the local file, then commit .gitignore.
  3. Coordinate history cleanup with the collaborator using GitHub’s procedure if required.
  4. Review access logs and enable safeguards against future secret commits.
# First add .env to .gitignore using your editor.
git rm --cached .env
git add .gitignore
git diff --cached
git commit -m "Stop tracking local secrets"

No comments yet.

Your answer

Sign in to share a solution.