In Simple Words#
- The problem
- Small mistakes reach the shared repository: lint errors, failing tests, a commit message like “fix stuff”. CI fails minutes later, and the whole team sees it.
- The root cause
- Nothing checks your work on your own computer. The first check happens only after you push, and each person follows the rules in a different way.
- The solution
- Add Git hooks: small scripts that Git runs before a commit and before a push. They stop a bad commit in seconds. Share them with Husky, and keep CI/CD as the second check.
- Think of it like this
- You read a letter one more time before you put it in the mailbox. A wrong word takes seconds to fix at your desk. After you send the letter, everyone who reads it sees the mistake.
Why Use Git Hooks?#
You commit a console.log by mistake. CI fails. You forgot the tests. Your commit message says “fix stuff.” Your team lead is not happy.
Git hooks stop that. A hook is a script that Git runs at a fixed point in your workflow: before a commit, before a push, after a merge. Hooks catch mistakes before anyone sees them.
What hooks prevent:
-
Bad code that reaches the repo
- Linting errors (a linter is a tool that finds common code mistakes), unused imports, formatting problems
- Failing tests
- Hardcoded secrets (passwords or API keys written in the code), vulnerable dependencies
- Syntax errors, type errors
-
Messy commit history
- Wrong message formats (
fix stuff→fix: resolve login timeout) - Missing issue numbers (a hook can require
feat: add dashboard (#123)) - Direct commits to protected branches
- Wrong message formats (
-
Wasted CI/CD minutes
- Problems are caught on your computer, so CI never runs on broken code
- Feedback in seconds, not minutes
-
Different rules for each person
- The same checks run for everyone, automatically
- Nobody can say “it works on my machine”
- The rules are applied, and nobody has to remind people
The hooks we really use:
| Hook | When It Runs | What It Checks | Skip It? |
|---|---|---|---|
pre-commit |
Before commit is saved | Linting, formatting, tests | git commit --no-verify |
commit-msg |
After commit message written | Message format, length | git commit --no-verify |
pre-push |
Before pushing to remote | Full test suite, build | git push --no-verify |
Tip: You can skip hooks with --no-verify. Do it only when you know what you are doing. One example: you fix a typo in the docs and do not want to run the full test suite.
Pre-commit Hook#
This hook checks code quality before each commit:
#!/bin/bash
# .git/hooks/pre-commit
echo "Running pre-commit checks..."
# 1. Lint code
npm run lint
if [ $? -ne 0 ]; then
echo "❌ Linting failed. Please fix errors before committing."
exit 1
fi
# 2. Run tests
npm test
if [ $? -ne 0 ]; then
echo "❌ Tests failed. Please fix failing tests before committing."
exit 1
fi
# 3. Check commit message format (if using commitlint)
npm run commitlint --edit $1
if [ $? -ne 0 ]; then
echo "❌ Commit message doesn't follow convention."
exit 1
fi
echo "✅ Pre-commit checks passed!"
exit 0Commit Message Hook#
This hook checks the format of the commit message:
#!/bin/bash
# .git/hooks/commit-msg
commit_msg=$(cat "$1")
# Check format: <type>(<scope>): <subject>
if ! echo "$commit_msg" | grep -qE "^(feat|fix|docs|style|refactor|perf|test|chore|ci|build)(\(.+\))?: .{1,50}"; then
echo "❌ Invalid commit message format!"
echo ""
echo "Format: <type>(<scope>): <subject>"
echo ""
echo "Types: feat, fix, docs, style, refactor, perf, test, chore, ci, build"
echo ""
echo "Example: feat(auth): add JWT authentication"
exit 1
fi
echo "✅ Commit message format is valid!"
exit 0Using Husky for Git Hooks#
Hooks that you write by hand in .git/hooks/ work, but you cannot share them with the team. Husky fixes that. It is a tool that keeps the hooks in a folder that Git tracks.
# Install husky
npm install --save-dev husky
# Initialize husky
npx husky install
# Add pre-commit hook
npx husky add .husky/pre-commit "npm test"
# Add commit-msg hook
npx husky add .husky/commit-msg "npx commitlint --edit $1"Why Husky?
- Shared - Git does not track
.git/hooks/, but it tracks.husky/ - Automatic - New team members get the hooks through
npm install - Cross-platform - Works on Windows, Mac, and Linux
- Simple - You only add scripts. You do not need to be good at bash
Integrating Hooks with CI/CD#
Hooks catch problems locally, on your computer. This is fast. CI/CD is the automatic pipeline on the server. It catches what the hooks missed, as a second check. Use both.
The plan:
- Pre-commit hook → Quick checks (linting, fast unit tests)
- Pre-push hook → Slower checks (full test suite)
- CI/CD pipeline → Everything + deployment
Example GitLab CI/CD pipeline:
# .gitlab-ci.yml
stages:
- lint
- test
- build
- deploy
# Run on all branches
lint:
stage: lint
script:
- npm run lint
only:
- branches
# Run on all branches
test:
stage: test
script:
- npm test
only:
- branches
# Build on all branches
build:
stage: build
script:
- npm run build
artifacts:
paths:
- dist/
only:
- branches
# Deploy develop → dev environment
deploy_dev:
stage: deploy
script:
- npm run deploy:dev
environment:
name: development
url: https://dev.example.com
only:
- develop
# Deploy staging → staging environment
deploy_staging:
stage: deploy
script:
- npm run deploy:staging
environment:
name: staging
url: https://staging.example.com
only:
- staging
# Deploy main → production (manual)
deploy_production:
stage: deploy
script:
- npm run deploy:prod
environment:
name: production
url: https://example.com
only:
- main
when: manualThe workflow:
- You run
git commit. Before Git saves the commit, the hooks run on your computer. pre-commitruns lint and tests. It finds a lint error in 5 seconds and stops the commit.- You fix the error and commit again.
pre-commitpasses, andcommit-msgaccepts the message format. - You run
git push.pre-pushruns the full test suite before the code leaves your computer. - The remote gets clean code. The CI/CD pipeline runs every check again and then deploys.
- Developer makes changes
- Pre-commit hook catches lint errors in 5 seconds
- Fix, commit again
- Pre-push hook catches failing tests in 30 seconds
- Push to remote
- CI/CD pipeline runs all checks + deployment
Common Hook Patterns#
1. Prevent Commits to Protected Branches#
Block direct commits to main:
#!/bin/bash
# .git/hooks/pre-commit
branch=$(git symbolic-ref HEAD | sed -e 's,.*/\(.*\),\1,')
if [ "$branch" = "main" ] || [ "$branch" = "master" ]; then
echo "❌ Direct commits to $branch are not allowed!"
echo "Create a feature branch instead:"
echo " git checkout -b feature/my-feature"
exit 1
fi2. Check for Hardcoded Secrets#
Catch API keys and passwords before the commit:
#!/bin/bash
# .git/hooks/pre-commit
# Check for common secret patterns
if git diff --cached | grep -qE '(api_key|API_KEY|password|PASSWORD|secret|SECRET)\s*='; then
echo "❌ Possible hardcoded secret detected!"
echo "Use environment variables instead."
exit 1
fi3. Auto-Format Code Before Commit#
Run Prettier on staged files (the files you added with git add):
#!/bin/bash
# .git/hooks/pre-commit
# Format staged files
npx prettier --write $(git diff --cached --name-only --diff-filter=ACM | grep -E '\.(js|jsx|ts|tsx|css|md)$')
# Re-stage formatted files
git add $(git diff --cached --name-only --diff-filter=ACM | grep -E '\.(js|jsx|ts|tsx|css|md)$')4. Require Issue Number in Commit Message#
Make every commit message name an issue:
#!/bin/bash
# .git/hooks/commit-msg
commit_msg=$(cat "$1")
# Check for issue number (#123)
if ! echo "$commit_msg" | grep -qE '\(#[0-9]+\)'; then
echo "❌ Commit message must reference an issue number!"
echo "Example: feat: add user login (#123)"
exit 1
fiTroubleshooting Hooks#
Hook Not Running#
Problem: The hook exists but does not run.
Solutions:
- Make it executable:
chmod +x .git/hooks/pre-commit - Check the shebang line:
#!/bin/bashmust be the first line - Check the name:
pre-commitnotpre-commit.sh
Hook Runs But Always Fails#
Problem: The script has errors.
How to debug:
# Run hook manually to see errors
bash .git/hooks/pre-commit
# Add debug output
echo "Debug: Current directory is $(pwd)"
echo "Debug: Git status:"
git statusNeed to Skip Hook Temporarily#
Solution:
# Skip pre-commit and commit-msg hooks
git commit --no-verify -m "fix: emergency hotfix"
# Skip pre-push hook
git push --no-verifyUse --no-verify only when you really must. It skips your safety checks.
Hooks Work Locally But Not for Team#
Problem: Git does not track .git/hooks/.
Solution: Use Husky (see Using Husky above). It stores hooks in .husky/, and Git DOES track that folder.
Conclusion#
Git hooks are your first check. Set them up once, and stop debugging CI failures.
Quick setup checklist:
- Install Husky:
npm install --save-dev husky - Initialize hooks:
npx husky install - Add pre-commit linting:
npx husky add .husky/pre-commit "npm run lint" - Add the commit-msg check:
npx husky add .husky/commit-msg "npx commitlint --edit $1" - Add auto-install:
"prepare": "husky install"in package.json - Test: make a commit and check that the hooks run
- Commit
.husky/to share with the team
Catch mistakes on your computer before they reach review or break CI.
Hands-On Implementation Guide#
Do you want to see this in a real project? The practical guide sets up Husky, lint-staged, and commitlint in a real Astro blog, step by step:
Implementing Git Hooks with Husky: A Real-World Example →
It covers:
- Step-by-step Husky installation with terminal output
- Commitlint config for conventional commits
- Lint-staged for faster pre-commit checks (6-10x faster)
- GitLab CI/CD integration
- Real troubleshooting from problems we had
- Time saved, before and after
This is what we run on blog.stack101. It is well tested and ready for production.
Related reading:
- Git Branching Strategy: A Practical Case - The full workflow guide that this post belongs to
- How to Fix: Accidentally Committed to Main Branch - Recover from common Git mistakes