How do you stop secrets before they're committed using a pre-commit hook?

BeginnerHands-onGitleaks
Answer

Short answer

Run Gitleaks on staged changes in a Git pre-commit hook, so a commit containing a secret is blocked on the developer's laptop before it ever reaches the remote. The easiest way is the pre-commit framework with the official Gitleaks hook.

With the pre-commit framework

# .pre-commit-config.yaml (committed to the repo)
repos:
  - repo: https://github.com/gitleaks/gitleaks
    rev: v8.21.2
    hooks:
      - id: gitleaks
pip install pre-commit
pre-commit install          # each developer runs this once
git commit -m "add config"
# Detect hardcoded secrets.................................................Failed
# - hook id: gitleaks
# Finding: password = "S3cret!" ...

Plain Git hook (no framework)

# .git/hooks/pre-commit  (chmod +x)
#!/usr/bin/env bash
gitleaks git --pre-commit --staged --redact -v .    # older: gitleaks protect --staged

Limits

Hooks are local and optional — developers can skip them (git commit --no-verify) or never install them. That's why the CI check is mandatory as the real gate; the hook is the fast, friendly first line.

What to say in the interview

"We use the pre-commit framework with the Gitleaks hook to scan staged changes and block commits locally. Because hooks can be bypassed, the same scan runs in CI as a required check."

All Security Tools questions Roadmap: Gitleaks — secret scanning

More on Gitleaks