How to keep secrets and API keys out of your code


Illustration: a key with a padlock

At a glance

Audience
Developers & coders
Difficulty
Beginner
Time needed (minutes)
20 min
Last reviewed
Nov 22, 2026

What you need

  • A code repository (Git)
  • Access to the settings of the services whose keys you use

Attackers run automated searches for API keys, cloud credentials and database passwords in code repositories, and they find them within minutes of a push. Private repositories are not safe either: they are shared with contractors, copied to laptops and exposed when an account is compromised.

A secret in the repository should be treated as a secret that has leaked.

🗝️

Store

Secrets live in the environment or a secrets manager, never in code.

🚧

Block

A scanner stops a key before it is committed, and again before it is pushed.

🔄

Rotate

If one leaks, revoke and replace it first. Everything else comes after.

Step 1: Move secrets out of the code

Your code should read secrets when it runs, not contain them.

❌ In the code: anyone with the repository has your key

const stripe = new Stripe('sk_live_51H…');

✅ From the environment: the key never enters Git

const stripe = new Stripe(process.env.STRIPE_SECRET_KEY);
  • Locally: keep values in a .env file listed in .gitignore, and commit a .env.example with the names only, so others know what to set.
  • In production and teams: use a secrets manager (AWS Secrets Manager, Azure Key Vault, Google Secret Manager, HashiCorp Vault) or your CI service's encrypted secrets. They control who reads each secret, keep an audit log and make rotation easy.
  • Check the usual hiding places: framework settings, Docker Compose files, infrastructure-as-code and CI pipelines.

Step 2: Stop secrets before they are committed

Install a secret scanner as a pre-commit hook, so a commit containing something that looks like a key is refused on the developer's own computer. Gitleaks and TruffleHog are free and recognize the key formats of hundreds of services.

# .pre-commit-config.yaml
repos:
  - repo: https://github.com/gitleaks/gitleaks
    rev: vX.Y.Z  # the latest release, from the Gitleaks page
    hooks:
      - id: gitleaks

Then add a second line of defence on the server:

  1. Scan every pull request. Run the same scanner in continuous integration.
  2. Turn on push protection. GitHub's secret scanning with push protection, and GitLab's secret detection, block pushes that contain known key formats.

Step 3: Scan what is already there

Scan the whole history of each repository, not just today's files: a key deleted two years ago is still in the history, and still works if it was never revoked.

gitleaks git -v .

Treat every real finding as a leak, and follow the steps below.

Step 4: Limit what a key can do

Do

  • One key per application and environment
  • The fewest permissions it needs: read-only, one bucket, one project
  • Short-lived credentials: cloud roles, or OpenID Connect from CI to your cloud
  • Rotate on a schedule, and when someone leaves the team

Avoid

  • One "master" key shared by every system
  • Administrator keys for jobs that only read
  • Long-lived access keys stored in CI
  • Keys nobody owns, or knows how to revoke

If a secret leaks: the first hour

⚠ Revoke first

Deleting the file or rewriting history does not stop anyone who already copied the key. Only revoking it does, so do it before anything else, even in a private repository.

  1. Revoke or rotate the secret in the service that issued it, and deploy the new one.
  2. Check the service's logs since the key was exposed: unexpected sign-ins, API calls, new users, exports or cloud resources you did not create.
  3. Remove it from the code and history with git filter-repo or the BFG Repo-Cleaner, then ask everyone to clone again. Forks and caches may still hold the old history: that is why revoking comes first.
  4. Assess the impact. If the key reached personal information and there is a real risk of significant harm, a Canadian organization may have to report the breach to the Office of the Privacy Commissioner of Canada under PIPEDA, or a confidentiality incident under Quebec's Law 25.
  5. Close the gap. Find out how it happened; usually the answer is the pre-commit hook and push protection above.

Two-minute checklist

  • .env is in .gitignore, and .env.example holds names only.
  • A secret scanner runs before each commit and in CI.
  • Push protection is on for your organization.
  • Every key has one purpose, minimal permissions and an owner.
  • You know how to revoke each key in minutes.

Keep learning

Next: the habits that prevent the most common web flaws, and how to patch vulnerable dependencies.

All guides for developers →

  • Secrets
  • API keys
  • Git
  • Incident response

Sources

This guide was drafted with the help of AI from the public sources listed above, then checked and edited by the newsroom. See how we use AI.

Editor's Picks

The best of cybersecuritynews.ca, delivered to you weekly.

On Display
Illustration: an open package with a warning sign

How to find and fix vulnerable dependencies in your code

Illustration: a shield with a code symbol

Secure coding basics: the web flaws attackers use most, and how to prevent them

Bell Canada

Bell Canada says an “agentic” hacker stole enterprise customer data from its circuit-ordering system