Block secrets with a pre-commit hook in 5 minutes

A pre-commit hook is a script git runs before every commit, and if it exits with an error, the commit doesn't happen. Point it at a secret scanner such as gitleaks, and a staged API key stops the commit on your laptop, before it's in any history you'd have to rewrite. Five minutes covers installing gitleaks, writing the hook, and testing it with a fake key.

I tested everything below with gitleaks 8.30.1 and git 2.54 on a throwaway repository. The hook caught a made-up Stripe key on the first try. It also let a database URL with a password in it straight through, which is why the hook in this post checks file names as well.

Which secret scanner should the hook run?

There are three common open-source choices. Each one's own README describes how it works:

gitleaks detect-secrets TruffleHog
How it finds secrets Rules: key formats and entropy Plugins, compared against a baseline of known findings Over 700 detectors that can check a key against the provider's API
Pre-commit command gitleaks git --pre-commit --redact --staged --verbose detect-secrets-hook --baseline .secrets.baseline trufflehog git file://. --since-commit HEAD --results=verified --fail
Needs a network No No Yes, to verify keys
Best for A quick, local hook An old repo with many existing findings Fewer false alarms in CI
Licence MIT Apache 2.0 AGPL 3.0

A word on TruffleHog's hook: the one in its own .pre-commit-hooks.yaml uses --results=verified, so it blocks only keys it could confirm are live by calling the provider. A key that isn't active yet, or one it has no detector for, gets through, and verifying means the key is sent to that provider's API. That's a fine trade in CI. For a hook on a laptop, I want something fast that works offline and errs on the side of stopping me, so this post uses gitleaks.

Step 1: Install gitleaks

On a Mac:

Terminal
$ brew install gitleaks
$ gitleaks version
8.30.1

On Linux and Windows, the releases page has binaries, and the README lists Docker and Go as other options.

Step 2: Add the hook to a repository

Save this as .git/hooks/pre-commit in your repository. It does two checks: it refuses any .env file by name (.env.example is allowed), then runs the same gitleaks command that gitleaks' own pre-commit hook uses.

bash
#!/bin/sh
# 1. Refuse .env files by name (.env.example is allowed).
envfiles=$(git diff --cached --name-only --diff-filter=ACMR | grep -E '(^|/)\.env' | grep -v '\.env\.example$')
if [ -n "$envfiles" ]; then
  echo "pre-commit: not committing these files:"
  echo "$envfiles"
  echo "Unstage them with: git restore --staged <file>"
  exit 1
fi
# 2. Scan what is staged for anything that looks like a key.
exec gitleaks git --pre-commit --redact --staged --verbose

Then make it executable. Git ignores hooks that aren't:

Terminal
$ chmod +x .git/hooks/pre-commit

--staged scans only what you're about to commit, so the hook stays fast, and --redact keeps the secret out of the terminal output. The name check matches .env, .env.local, config/.env.production and also .envrc, which often holds keys too.

git commit runs a file-name check, then gitleaks; either one can refuse the commit, and only when both pass is the commit made
Two cheap checks, on your laptop, before anything is in git.

Prefer the pre-commit framework?

If your team already uses pre-commit, add gitleaks to .pre-commit-config.yaml instead. This is the config from gitleaks' README, with the version I tested:

yaml
repos:
  - repo: https://github.com/gitleaks/gitleaks
    rev: v8.30.1
    hooks:
      - id: gitleaks
Terminal
$ pip install pre-commit
$ pre-commit install
pre-commit installed at .git/hooks/pre-commit

This runs the gitleaks scan but not the file-name check; for that, keep the script above or add a local hook of your own. Teammates run pre-commit install once in their clone, because git never copies hooks from a repository.

Step 3: Test it with a fake key

Make a key that looks real but isn't. This writes a random value with Stripe's live-key prefix, so nothing real is ever typed or committed:

Terminal
$ printf 'STRIPE_KEY=sk_live_%s\n' "$(openssl rand -hex 16)" > config.env
$ git add config.env
$ git commit -m "add config"
Finding:     STRIPE_KEY=REDACTED
Secret:      REDACTED
RuleID:      stripe-access-token
Entropy:     4.158695
File:        config.env
Line:        1
Fingerprint: config.env:stripe-access-token:1
 
5:20PM INF 0 commits scanned.
5:20PM INF scanned ~52 bytes (52 bytes) in 77.8ms
5:20PM WRN leaks found: 1

That's the real output, minus the gitleaks logo at the top. The commit wasn't made. Now try a .env file:

Terminal
$ git add .env.local
$ git commit -m "db"
pre-commit: not committing these files:
.env.local
Unstage them with: git restore --staged <file>

Clean up the test file afterwards with git restore --staged config.env and rm config.env.

What does gitleaks miss?

Secrets with no recognisable shape. In my test, this .env.local went past gitleaks without a finding:

bash
DATABASE_URL=postgres://app:Winter2026blue@db.example.com:5432/app
ADMIN_PASSWORD=correct-horse-battery
text
5:20PM INF scanned ~104 bytes (104 bytes) in 90.9ms
5:20PM INF no leaks found

A scanner finds keys by their format (sk_live_, ghp_, AKIA) or by how random they look. A password made of words has neither. That's what the file-name check is for: the place such passwords usually live is a .env file, and the hook refuses those whatever is inside.

The deeper limit is that a scanner guesses. It doesn't know which strings are your real secrets. A check that compares staged changes with the values you use would catch the database password above. That's the idea behind a leak check and pre-commit hook I plan for Keyfold, listed under "Next" on the roadmap: "Find vault values sitting in your code or git history, and block commits that contain them." It isn't in the app yet.

Step 4: Use the hook in every repository

Hooks live in each repository's .git/hooks folder, which is easy to forget for new clones. Git's core.hooksPath setting points every repository at one folder instead:

Terminal
$ mkdir -p ~/.git-hooks
$ cp .git/hooks/pre-commit ~/.git-hooks/pre-commit
$ git config --global core.hooksPath ~/.git-hooks

I tested this with a fresh repository: the global hook refused a .env file there with no setup in the repository itself. Two things to know. With core.hooksPath set, git runs hooks from that folder only, so hooks in a repository's own .git/hooks stop running. And a repository that sets its own core.hooksPath, as some JavaScript hook managers do, overrides your global one.

What if the hook flags something that isn't a secret?

Test fixtures and example keys trigger it sometimes. gitleaks gives you two ways out, both in its README:

  • Add a gitleaks:allow comment on the line, if you knowingly commit a test value.
  • Add the finding's fingerprint (the Fingerprint: line in the output) to a .gitleaksignore file in the repository root.

To skip the hook for one commit, git commit --no-verify bypasses the pre-commit hook; with the pre-commit framework, SKIP=gitleaks git commit skips only gitleaks. Anyone can do this, and so can an AI agent that makes commits for you. If you work with one, say in its instructions that it must never use --no-verify.

Why keep GitHub's push protection on too?

Because a hook only runs where it's installed and can be skipped. GitHub's push protection is the second net, on GitHub's side. Push protection for users is "enabled by default" and "stops you from pushing secrets to public repositories". Push protection for repositories, which covers private ones, needs GitHub Secret Protection and is off by default.

A pre-commit hook and push protection compared: where each runs, whether it works offline, private repositories, setup and how it's skipped
The hook stops it earlier; push protection covers machines without the hook.

Private repositories are where the local hook matters most. GitGuardian's State of Secrets Sprawl 2026 found internal repositories "roughly 6× more likely than public ones to contain hardcoded secrets", and the free, default push protection doesn't cover them.

The surest fix is still a key that was never in the repository: loaded at run time from somewhere encrypted. With Keyfold that's keyfold run -p acme-api -e development -- npm test, with keys kept by project and environment in one file. If a key does get through, the ten-minute plan for a leaked key puts rotation first. The security page explains how Keyfold stores keys.

FAQ

Does a pre-commit hook slow down commits?

Barely, with --staged. In my test gitleaks scanned the staged change in under 100 milliseconds. A full history scan is slower, which is why that's a one-off command, not part of the hook.

Can I share the hook with my team through the repository?

Not through .git/hooks, which git never copies. Either commit a .pre-commit-config.yaml and ask everyone to run pre-commit install, or commit the script to a folder such as scripts/ and ask everyone to point core.hooksPath at it.

Is gitleaks or detect-secrets better?

For a new repository and one person, gitleaks is simpler to start with. detect-secrets suits a large existing repository: its baseline records what's already there and blocks only new findings.

Does the hook catch secrets an AI agent writes?

Yes, for commits made on that computer: the hook runs whoever runs git commit. It can't stop an agent that skips it with --no-verify, or one that pastes a key into a chat instead of a file.

What should I do if the hook finds a real key I already committed?

The hook only blocks new commits. If the key is in earlier commits, or was ever pushed, rotate it, then remove it from history.