What Is a Pre-Commit Hook?
A pre-commit hook is a script that runs just before a commit is recorded, able to check or fix the changes and block the commit if something is wrong.
A pre-commit hook is the most popular Git hook because it catches problems at the earliest possible moment, before a commit even exists. It runs your checks, linting, formatting, secret scanning, on the staged changes, and can stop the commit if they fail, keeping bad code out of history.
When it runs
The pre-commit hook fires after you run git commit but before the commit is finalized. It inspects the staged changes and exits with success or failure. A non-zero exit aborts the commit, so the developer fixes the issue and tries again, all without anything entering history.
Common pre-commit checks
- Linting and code formatting on staged files.
- Scanning for accidentally staged secrets or keys.
- Running quick unit tests on changed code.
- Blocking large files or forbidden patterns.
Managing pre-commit hooks
Because raw hooks live outside version control, teams use frameworks to define and share them so everyone gets the same checks.
# .pre-commit-config.yaml
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.6.0
hooks:
- id: trailing-whitespacePre-commit hooks and CI/CD
Running the same lint and format checks locally as a pre-commit hook means most issues are caught before code is pushed, so CI fails far less often on trivial problems. This shortens the feedback loop and saves CI minutes. CI still re-runs the checks as the authoritative gate, since hooks can be skipped.
Pre-commit best practices
- Keep hooks fast so they do not slow down committing.
- Mirror key CI checks locally to catch issues early.
- Use a framework to share hooks across the team.
- Rely on CI as the enforced gate, hooks as the early one.
Key takeaways
- A pre-commit hook runs checks before a commit is recorded.
- It catches lint, formatting, and secret issues at the earliest point.
- It shortens the CI feedback loop but does not replace the CI gate.