An API key that ends up published on GitHub is almost never the result of one dramatic moment of carelessness. It's almost always the consequence of a misunderstood tooling detail: a .gitignore added after the first commit, a build tool that inlines variables without warning, or a git history people assume is "clean" simply because the file no longer shows up in the current working tree. Understanding the exact mechanism behind each leak is what lets you block it at the source instead of reacting after the fact.

The late .gitignore trap

Adding .env to .gitignore has zero effect on files git is already tracking. Git only ignores untracked files; if .env was committed even once, even all the way back in the project's very first commit, it stays in history indefinitely, even after being deleted and ignored afterward.

# This commit does NOT remove .env from history
git rm --cached .env
echo ".env" >> .gitignore
git commit -m "chore: remove env file from tracking"
# .env is still readable through:
git show <initial-commit>:.env

Actually cleaning it up requires rewriting history with git filter-repo (or, as a last resort, BFG Repo-Cleaner), then force-pushing, coordinated with the whole team since it rewrites every SHA downstream. And even after that: any secret that was pushed publicly must be treated as compromised and rotated, not just erased from history. A public history, even briefly, could have been cloned, cached by mirrors, or indexed.

The false sense of safety from "it's backend, so it's fine"

An environment variable is not automatically private. In most modern frontend frameworks, a prefix convention explicitly determines what gets exposed to the browser:

# .env - Next.js
DATABASE_URL=postgres://user:pass@host:5432/db      # stays server-side
NEXT_PUBLIC_API_BASE_URL=https://api.example.com     # inlined into the JS bundle

Vite uses VITE_, Create React App used REACT_APP_. The danger comes from the reverse confusion: a developer reflexively prefixing a sensitive key (a third-party API key, a signing secret) with NEXT_PUBLIC_ or VITE_ "because it's easier to access in the component." The build tool then literally inlines it in plaintext into the JavaScript served to the browser, visible to anyone through devtools, completely independent of any git repository.

// This exposes the key in the final bundle, not just in the repo
const stripeSecret = process.env.NEXT_PUBLIC_STRIPE_SECRET_KEY;

The rule is simple and non-negotiable: any secret that must stay confidential never carries the public prefix, and must be consumed exclusively server-side (an API route, a server action, a separate backend), never imported into a component that runs on the client.

Secrets leaking through CI/CD logs

A CI pipeline that does echo $API_KEY for debugging, or logs the full command it runs including its arguments, leaves the secret in plaintext in the build logs, often visible to the whole team or even publicly depending on the repo's configuration. GitHub Actions automatically masks the values of secrets declared through secrets.*, but only if the variable actually goes through that mechanism, and only if it appears unchanged (a secret that's base64-encoded or concatenated with other text escapes the masking).

# .github/workflows/deploy.yml
- name: Deploy
  env:
    API_KEY: ${{ secrets.API_KEY }}
  run: |
    echo "Deploying with key: $API_KEY"   # shows up masked in GitHub logs
    curl -H "Authorization: Bearer $API_KEY" https://...  # same, if declared as a secret

The real risk comes from scripts that transform the secret before using it (encoding, splitting, interpolating it into a URL): the transformed value is no longer recognized as the original secret and therefore isn't masked.

Diagnosing a leak that already happened

Before panicking or reacting at random, establish precisely what leaked and where. git log -p -- .env shows the file's full history if it was ever tracked. Tools like trufflehog or gitleaks scan an entire repository's history for known secret patterns (AWS keys, Stripe tokens, private keys) and produce an exhaustive list instead of a guess.

gitleaks detect --source . --log-opts="--all" --report-path gitleaks-report.json

This diagnostic step is the one most commonly skipped in a panic, even though it's the only way to know whether the incident involves one file or ten, a single commit or an entire history.

The architecture that actually prevents a repeat

The durable fix isn't personal discipline ("I'll be more careful"), it's an architecture that makes the mistake either impossible or immediately visible:

  • A versioned .env.example, with variable names but fake values, so onboarding never involves copying an existing real .env.
  • A dedicated secret manager (Doppler, Vault, AWS Secrets Manager, or the deployment platform's native "Environment Secrets") instead of .env files passed around over Slack or copied from one machine to another.
  • A pre-commit hook (gitleaks protect or git-secrets) that blocks the commit before it ever enters history, rather than scanning after the fact.
# .pre-commit-config.yaml
repos:
  - repo: https://github.com/gitleaks/gitleaks
    rev: v8.18.4
    hooks:
      - id: gitleaks
  • Systematic rotation of any secret that ever traveled through an unaudited channel (email, chat, a shared plaintext file), regardless of whether a leak was actually confirmed.

When rotation alone isn't enough

Revoking and regenerating an API key cuts off future access, but it fixes nothing if the compromised secret was already used to exfiltrate data or create resources (cloud instances, IAM users, webhooks) during the exposure window. In that case, rotation has to be paired with an audit of the affected service's access logs (CloudTrail for AWS, Stripe's API logs, and so on) covering the entire period the secret was exposed, to verify no illegitimate action took place. That step usually goes beyond what a single developer can handle alone and belongs in a formal incident-response process involving the security team or the hosting provider.

The Docker image trap

An ARG or a variable injected during docker build looks like it disappears once the container reaches production, but it actually stays printed in the metadata of every image layer, inspectable with docker history or by examining the filesystem of the relevant layer, even if a later Dockerfile step removes it from the final filesystem.

# Bad: the secret stays visible in the image's history
ARG NPM_TOKEN
RUN echo "//registry.npmjs.org/:_authToken=${NPM_TOKEN}" > .npmrc && \
    npm install && \
    rm .npmrc
# docker history <image> still shows the full command with the token in plaintext

The correct approach uses BuildKit's dedicated build secrets, which mount the secret only for the duration of the instruction that needs it, without ever writing it into a persistent image layer:

# syntax=docker/dockerfile:1
RUN --mount=type=secret,id=npm_token \
    NPM_TOKEN=$(cat /run/secrets/npm_token) && \
    echo "//registry.npmjs.org/:_authToken=${NPM_TOKEN}" > .npmrc && \
    npm install && rm .npmrc
docker build --secret id=npm_token,src=./npm_token.txt .

This mechanism guarantees the secret never appears in any intermediate layer of the final image, unlike a classic ARG or ENV.

Relying on platform-level push protection as a last line of defense

GitHub's push protection (enabled by default on public repositories and available on private ones with GitHub Advanced Security) scans commits for recognizable secret patterns before they're accepted on push, and can reject the push outright. It's a useful safety net, but it only recognizes known provider formats (AWS, Stripe, common cloud providers) and can be bypassed entirely through a force-push from a client where the check wasn't run, or simply doesn't cover self-hosted Git servers. It should be treated as a backstop that catches what the pre-commit hook missed, never as the primary control.

Takeaway: a leaked secret is almost always a mechanism problem, not a vigilance problem. Removing .env from git tracking doesn't erase it from history, prefixing a variable as "public" inlines it into the client bundle, and the only reliable response to a confirmed leak is immediate rotation of the secret, never just its removal from the code.