How to Protect Your API Keys from Leaking on GitHub (2026 Checklist)

How to Protect Your API Keys from Leaking on GitHub (2026 Checklist)

A single API key pushed to a public GitHub repo can cost a team real money before anyone notices. Bots scan public commits within minutes, and a leaked key for a cloud provider or an AI service gets tested almost immediately. Learning how to protect API keys from leaking on GitHub is no longer optional for developers who ship code in public repos or in private repos with outside collaborators. This checklist walks through the habits, tools, and settings that keep secrets out of your history.

The stakes are easy to underestimate. Attackers use a leaked key to spin up servers, send spam, or query paid APIs on your bill, and some teams only find out when the invoice arrives. The fixes below cost minutes to set up.

Why Leaked Keys Get Found So Fast

GitHub is public by default for open source, and its search and API make it easy to scan new commits at scale. Automated scanners watch the public event feed, clone fresh repos, and grep for patterns that look like tokens: long strings after api_key=, AKIA prefixes, private key blocks, and bearer tokens in headers. A key can be copied within minutes of the push, and deleting the commit afterwards does not help, because forks, clones, and cached copies already hold it.

Private repos are safer but not safe. Contractors and former team members may keep local clones, and a repo that turns public later exposes its full history, including every secret ever committed. Git history keeps secrets alive long after the file is deleted from the current version, which is why prevention matters more than cleanup.

How to Protect API Keys from Leaking: The 2026 Checklist

Work through these six items in order. Each one closes a different hole, and together they cover the most common ways keys escape into Git.

1. Keep secrets out of Git with .gitignore

The first rule is simple: never commit api keys in git, in any form. No .env files, no config files with real values, no screenshots of dashboards, no Postman collections with live tokens. Add .env, .env.local, *.pem, and credentials.json to your .gitignore before you write your first line of code, and commit a .env.example with placeholder values instead so teammates know which variables the app needs.

Check the ignore file actually works. Run git status after creating a local .env and confirm it does not appear. A surprising number of leaks happen because the ignore rule was added after the file was already tracked, and Git keeps tracking files it already knows about. If that happened to you, run git rm --cached .env and commit the removal, then rotate the key, because the old value still sits in history. Our guide on how to secure your Git repositories covers the full repo hardening routine, including branch protection and signed commits.

2. Use environment variables, never hardcode

Read keys from the environment at runtime instead of pasting them into source files. In Node, that means process.env.STRIPE_KEY. In Python, os.environ["OPENAI_API_KEY"]. In Go, os.Getenv. The code stays identical across machines, and the secret lives in the deployment platform, the CI runner, or a local .env file that never reaches Git.

For the full pattern, including where each kind of secret belongs, read our practical guide to storing API keys and secrets safely, which compares environment variables, vaults, and cloud secret stores side by side.

3. Use a secrets manager for shared keys

Once more than two people need the same key, a shared .env file passed around in chat becomes a leak waiting to happen. A secrets manager gives each developer and each server access to exactly the keys it needs, with an audit trail of who read what and when. It also makes rotation a one-place change instead of a message to the whole team asking everyone to update their local files.

Good options for small teams include HashiCorp Vault, AWS Secrets Manager, and Doppler, and the choice depends on where your infrastructure already lives. This comparison of Vault, AWS Secrets Manager, and Doppler lays out the trade-offs in price and setup effort. If your team already uses 1Password, its CLI can inject secrets into local development without anyone seeing the raw value, and our comparison of Vault, 1Password CLI, and SOPS shows how that setup works in practice.

4. Turn on GitHub secret scanning

GitHub secret scanning checks every push against known token formats from dozens of providers and alerts you when it finds a match. On public repos it runs by default. On private repos, enable it in Settings, then Security, then Code security. Push protection goes one step further: it blocks the push entirely when it detects a secret, instead of warning you after the fact.

Push protection is the single highest-value setting on this list, because it catches the mistake at the moment it happens, when the fix is still cheap. Turn it on for every repo that holds application code, not just the main one. The github secret scanning feature also supports custom patterns, so you can add your own token formats for internal services that GitHub does not know about.

5. Rotate api keys on a schedule, and limit their scope

A key that never rotates is a key that stays useful to an attacker for years. Rotate api keys every 90 days at minimum, and rotate immediately when someone leaves the team, when a laptop is lost, or when a repo changes visibility. Automate rotation where the provider supports it, and put the next rotation date in your team calendar so it does not depend on memory.

Scope matters as much as rotation. Give each key the smallest permission it needs: read-only where read-only is enough, a single environment instead of all of them, an expiry date instead of forever. A leaked read-only key for a staging database is an incident. A leaked admin key for production is a crisis. Separate keys per environment, per service, and per developer where you can, so revoking one key does not break everything else.

6. Scan your history and your CI logs

Run a scanner over your repos before you assume they are clean. Tools like Gitleaks and TruffleHog scan the full commit history, including deleted files and old branches, and report anything that looks like a credential. Run one in CI on every pull request so a secret never reaches the default branch, and run a full-history scan once a quarter.

Check CI logs too. A common leak is a test step that prints the environment for debugging and leaves the key in a log that anyone with repo access can read. Mask secrets in your CI config and treat build logs as semi-public.

What to Do When a Key Leaks

Assume the key is already copied. Revoke it first, then investigate. Revoking stops the bleeding, and every minute of delay is a minute an attacker can use the key. Create a replacement key, update every place that uses it, and confirm the old one returns an error before you move on.

Next, check what the key touched. Review provider logs for the window between the leak and the revocation: unusual regions, odd hours, spikes in usage, new resources you did not create. If the key had write access, check for changes made with it. If customer data could have been reached, follow your incident plan and tell the people affected. The 72-hour data breach response plan gives a clear order of operations for exactly this situation.

Common Mistakes That Still Cause Leaks

Hardcoding a key “just for testing” and forgetting to remove it is the classic one. Test keys have a way of reaching production, and providers rarely distinguish between a test key and a real one when billing. Use clearly marked dummy values in tests and load real keys only from the environment.

Committing a Jupyter notebook or a database dump is another. Notebooks store cell outputs, which often include tokens printed during debugging. Dumps include config tables. Scrub both before committing, or keep them out of Git entirely.

Frequently Asked Questions

Does deleting a commit remove a leaked key from GitHub?

No. Deleting the commit does not remove it from history, forks, or cached copies. The only safe response is to revoke the key and issue a new one.

Is .gitignore enough to protect API keys?

It is the first layer, not the whole defence. Gitignore stops accidental commits of files you know about. It does not stop a teammate pasting a key into a code file, a CI log printing a secret, or a key hidden in a notebook output. Pair it with push protection, a secrets manager, and regular history scans.

Ditulis oleh

Firdaus Safari Putra

Founder, PT FirKaizen Digital Solutions

Firdaus Safari Putra adalah founder PT FirKaizen Digital Solutions. Ia membangun dan mengoperasikan infrastruktur server di balik panduan ini, dan menulis berdasarkan apa yang benar-benar ia jalankan, uji, dan ukur — bukan teori.