Accidentally committing an API key is one of the most common security mistakes, and AI-assisted coding has made it more common: studies have found AI-assisted commits expose secrets at a noticeably higher rate than human-only ones.

If it happens, speed matters. Bots scan public repositories for keys continuously.

Step 1: Rotate the secret immediately

Revoke and replace the key first. Rewriting git history comes later, and it does not help if the key was already copied.

  • Generate a new key in the provider's dashboard.
  • Update it wherever it is used (environment variables, secret managers, CI).
  • Revoke the old key.
  • Check the provider's logs for use of the old key.

Step 2: Remove it from the code

Move the value to an environment variable or secret manager and read it at runtime.

typescript
const apiKey = process.env.PAYMENTS_API_KEY;
if (!apiKey) throw new Error("PAYMENTS_API_KEY is not set");

Add local env files to .gitignore and commit a .env.example with placeholder values instead.

Step 3: Clean the history (if needed)

Deleting the file in a new commit leaves the secret in history. For a repository where history matters, rewrite it with git filter-repo:

bash
git filter-repo --replace-text replacements.txt
# replacements.txt contains a line like:
# sk_live_abc123==>REDACTED

Then force-push and ask collaborators to re-clone. On hosted platforms, cached views and forks may still contain the old commit, which is why rotation in step 1 is essential.

Step 4: Find other leaks

Scan the whole history, not only the current files:

bash
gitleaks detect --source . --log-opts="--all"

Tools like gitleaks and trufflehog detect common key formats and high-entropy strings.

Prevent it next time

  • Pre-commit scanning – run a secret scanner as a pre-commit hook so leaks are blocked locally.
  • Push protection – enable secret scanning and push protection on your git host.
  • Short-lived credentials – prefer OIDC and temporary tokens in CI over long-lived keys.
  • Scoped keys – give each key the minimum permissions and, where possible, IP or referrer restrictions.
  • Tell your AI tools – include "never hard-code secrets; use environment variables" in your project instructions.

Key takeaways

  • Rotate first, clean up second.
  • Removing a file does not remove it from git history.
  • Scan the full history and enable push protection.
  • Pre-commit hooks and short-lived credentials prevent repeat incidents.