Automating Quality Gates with Git Hooks
11 min read
What Are Git Hooks?
Git hooks are shell scripts that Git executes automatically at specific points in the workflow — before a commit, after a push, before a rebase, and more. They live in .git/hooks/ and run locally on every developer's machine.
Most Useful Hooks
pre-commit— runs before the commit message editor opens. Ideal for linting and formatting checks.commit-msg— receives the commit message file path. Use it to enforce message conventions.pre-push— runs beforegit push. Great for running the test suite to block broken pushes.post-merge— runs after a successful merge. Common use:npm installwhenpackage.jsonchanged.
Writing a pre-commit Hook
bash
# .git/hooks/pre-commit (must be executable: chmod +x .git/hooks/pre-commit)
#!/usr/bin/env bash
set -e
echo "Running ESLint..."
npx eslint --max-warnings=0 src/
echo "Running type-check..."
npx tsc --noEmitIf the script exits with a non-zero code, Git aborts the commit. The developer sees the error output and must fix it before committing.
Sharing Hooks with the Team
Because .git/hooks/ is not committed to the repository, hooks are not automatically shared. Two popular solutions:
- Husky (
npm install --save-dev husky) — stores hooks in.husky/(which IS committed) and registers them via apreparescript. - `core.hooksPath` — point Git to a committed directory:
git config core.hooksPath .githooks.
At CPCODELAB, Husky is the standard. When you clone a repo and run npm install, the prepare script automatically installs hooks for you. Never bypass hooks with git commit --no-verify except in a genuine emergency, and always follow up with a fix.
Ready to test yourself?
Practice Git & GitHub— quiz & coding exercises