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."
More on Gitleaks
What is Gitleaks and how do you use it?BeginnerWhat is a secret leak and why is it dangerous?BeginnerWhat is Gitleaks?BeginnerHow do you scan a repository's full history with Gitleaks and create a report?BeginnerHow do you run Gitleaks in a CI pipeline and fail the build on findings?BeginnerGitleaks found a real AWS key in the repo. What do you do?Beginner