Why This Guide?#
Most hook tutorials stop at theory. This one shows a real setup in a real Astro blog on GitLab: real config, real output, real troubleshooting.
At the end you have working hooks that catch errors before CI/CD runs.
In Simple Words#
- The problem
- You push a commit and wait 3-5 minutes for CI. Then CI fails on a lint error. You fix it, push again and wait again.
- The root cause
- Nothing checks the code or the commit message on your computer. And Git does not track hooks in
.git/hooks/, so the team does not get them. - The solution
- Install Husky, lint-staged and commitlint. Now every
git commitlints the staged files and checks the message in a few seconds. GitLab CI runs the same checks again as a backup. - Think of it like this
- You check a form at home before you go to the office. A missing field takes seconds to fix at home. At the office, you would wait in line and then be sent back.
What We’re Building#
Three checks for the blog.stack101 project:
- Pre-commit hook → ESLint and Prettier run only on staged files, the files you added with
git add(fast) - Commit message check → Every message must follow the conventional commit format (
type: subject) - GitLab CI/CD integration → The same checks run in the pipeline as a backup
- You run
git commit. Husky starts the hook files in.husky/. pre-commitruns lint-staged. ESLint and Prettier check only the staged files, in 2-3 seconds.commit-msgruns commitlint. The message “add git-hook-implementation post” has no type, so the commit is stopped.- You write
feat: add git-hook-implementation post. Both hooks pass and Git creates the commit. - In GitLab, the
lintstage runs the same checks again. It also catches people who skip hooks with--no-verify.
Why these?
- Lint errors are caught in
<5seconds on your computer, not after 2+ minutes in CI - The whole team writes commit messages in the same format
- Broken builds never reach GitLab
Prerequisites#
You need:
- A Node.js project with
package.json - A Git repository (GitLab, GitHub, or any host)
- ESLint (finds code mistakes) and Prettier (formats code), already set up
- Read this guide: https://typicode.github.io/husky/get-started.html
Current state of blog.stack101:
# What we have
- ESLint with @typescript-eslint + astro plugins
- Prettier with astro + tailwind plugins
- GitLab CI/CD pipeline (.gitlab-ci.yml)
# What we DON'T have yet
- Husky
- Git hooks
- Commit message validationStep 1: Install Husky#
Husky stores hooks in .husky/, a folder that Git tracks. Git does not track .git/hooks/. So with Husky the whole team gets the hooks.
# Install Husky
npm install --save-dev husky
# Initialize Husky (creates .husky/ directory)
npx husky initWhat this did:
- Added Husky to
package.jsondevDependencies - Created the
.husky/directory with setup files - The hooks are now in version control
Check Prepare Script#
Your package.json needs this:
{
"scripts": {
"prepare": "husky"
}
}prepare runs after npm install. You clone, you install, and the hooks are ready. There are no extra steps.
Step 2: Install Commitlint#
Commitlint checks that commit messages follow the conventional commit format.
# Install commitlint packages
npm install --save-dev @commitlint/cli @commitlint/config-conventional@commitlint/cli- The command line tool that checks commit messages@commitlint/config-conventional- Ready-made rules for conventional commits
Create Commitlint Configuration#
Use the .cjs extension if your package.json has "type": "module".
Create commitlint.config.cjs in the project root:
// commitlint.config.cjs
module.exports = {
extends: ['@commitlint/config-conventional'],
rules: {
'type-enum': [
2,
'always',
[
'feat', // New feature
'fix', // Bug fix
'docs', // Documentation changes
'style', // Formatting (no code change)
'refactor', // Refactoring production code
'perf', // Performance improvements
'test', // Adding tests
'build', // Build system changes
'ci', // CI/CD changes
'chore', // Maintenance tasks
'revert', // Reverting changes
],
],
'subject-case': [2, 'never', ['upper-case', 'pascal-case', 'start-case']],
'subject-max-length': [2, 'always', 72],
'body-max-line-length': [2, 'always', 100],
},
}What this sets up:
- The standard conventional commit rules
- A fixed list of commit types
- Lowercase subjects only
- Subject of 72 characters at most (fits in git logs)
- Body of 100 characters per line at most
Step 3: Install Lint-Staged#
Lint-staged runs linters only on staged files. This is much faster than linting the whole codebase.
# Install lint-staged
npm install --save-dev lint-stagedCreate Lint-Staged Configuration#
Create .lintstagedrc.json in the project root:
{
"*.{js,jsx,ts,tsx,astro}": ["eslint --fix", "prettier --write"],
"*.{md,mdx,json,css,scss}": ["prettier --write"]
}How it works:
- It matches staged files by extension
- It runs the commands one after another for each match
- It fixes what it can and stages the fixed files again
TypeScript/Astro files get ESLint + Prettier. Markdown/CSS get Prettier only.
Step 4: Create Pre-Commit Hook#
This hook runs before Git creates the commit.
If npx husky init created .husky/pre-commit with npm test, replace that content.
Edit the File Directly (Recommended)#
# .husky/pre-commit
npx lint-stagedWhat happens:
- It starts before the commit
- It runs lint-staged on staged files only
- Linting fails → the commit is stopped
- Linting passes → the commit continues
Step 5: Create Commit-Msg Hook#
This hook checks the commit message after you write it.
husky add is deprecated in v9, so you should not use it any more. Create the file by hand.
Create the File Manually#
# Create .husky/commit-msg file
echo 'npx --no -- commitlint --edit "$1"' > .husky/commit-msg
# Make it executable
chmod +x .husky/commit-msgOr create .husky/commit-msg with your editor:
npx --no -- commitlint --edit "$1"What happens:
- It starts after you write the commit message
- It checks the message against the commitlint rules
- Invalid → the commit is stopped with an error
- Valid → the commit continues
The --no flag stops npx from asking to install commitlint when it is missing. It fails at once instead.
Step 6: Update Package.json Scripts#
Add helper scripts so you can lint and format by hand:
{
"scripts": {
"dev": "astro dev",
"start": "astro dev",
"build": "astro build",
"preview": "astro preview",
"deploy": "npm run build && wrangler pages deploy dist",
"prepare": "husky install",
"lint": "eslint --ext .js,.ts,.astro src/",
"lint:fix": "eslint --ext .js,.ts,.astro src/ --fix",
"format": "prettier --write \"src/**/*.{js,ts,astro,md,mdx,json,css,scss}\"",
"format:check": "prettier --check \"src/**/*.{js,ts,astro,md,mdx,json,css,scss}\""
}
}prepare- Installs Husky automatically afternpm installlint/lint:fix- Check linting errors, or fix them automaticallyformat/format:check- Format files, or only check the formatting (CI usesformat:check)
Step 7: Test the Hooks#
This is real output from the blog.stack101 project.
Test 1: Bad Commit Message (Should Fail)#
# Stage your changes
git add .
# Try to commit without conventional format
git commit -m "add git-hook-implementation post"Real output:
✔ Backed up original state in git stash (eb9c24a)
✔ Running tasks for staged files...
✔ Applying modifications from tasks...
✔ Cleaning up temporary files...
⧗ input: add git-hook-implementation post
✖ subject may not be empty [subject-empty]
✖ type may not be empty [type-empty]
✖ found 2 problems, 0 warnings
ⓘ Get help: https://github.com/conventional-changelog/commitlint/#what-is-commitlint
husky - commit-msg script failed (code 1)Pre-commit passed, but commit-msg rejected the commit. The message has no type prefix.
Test 2: Valid Commit Message (Should Pass)#
# Try again with correct format
git commit -m "feat: add git-hook-implementation post"Real output:
✔ Backed up original state in git stash (312c658)
✔ Running tasks for staged files...
✔ Applying modifications from tasks...
✔ Cleaning up temporary files...
[feat/git-hooks-implementation 554a71c] feat: add git-hook-implementation post
12 files changed, 2600 insertions(+), 129 deletions(-)
create mode 100755 .husky/commit-msg
create mode 100755 .husky/pre-commit
create mode 100644 .lintstagedrc.json
create mode 100644 commitlint.config.cjs
create mode 100644 public/projects/git-hooks-implementation/.gitkeep
create mode 100644 public/projects/git-hooks-implementation/code-structure.png
create mode 100644 public/projects/git-hooks-implementation/featured.webp
create mode 100644 src/content/blog/git-hooks-implementation.mdxBoth hooks passed. The commit was created.
Test 3: Linting Errors (Should Fail)#
Create a file with errors on purpose:
// src/broken.js
const unused = 'variable' // ESLint will catch this
console.log('missing semicolon')# Stage and try to commit
git add src/broken.js
git commit -m "test: add broken file"Expected output:
npx lint-staged
✔ Preparing lint-staged...
⚠ Running tasks for staged files...
❯ *.{js,jsx,ts,tsx,astro} — 1 file
✖ eslint --fix [FAILED]
◼ prettier --write
✖ eslint --fix:
/Users/su/Projects/blog.stack101/src/broken.js
1:7 error 'unused' is assigned a value but never used @typescript-eslint/no-unused-vars
2:1 error Missing semicolon semi
✖ 2 problems (2 errors, 0 warnings)
1 error and 0 warnings potentially fixable with the `--fix` option.
husky - pre-commit hook exited with code 1 (error)The commit is blocked.
Step 8: Integrate with GitLab CI/CD#
Hooks catch errors on your computer. CI/CD is the backup. It catches commits from people who skipped the hooks, and from outside contributors.
Update .gitlab-ci.yml#
Add a lint stage with two jobs:
# GitLab CI/CD pipeline for Astro blog deployment to Cloudflare Pages
image: node:24
stages:
- lint # ← Add this stage
- install
- build
- test
- deploy
# ==========================================
# STAGE 0: LINT (runs first)
# ==========================================
# Job 1: Validate Code Quality
lint:code:
stage: lint
script:
- echo "Running code quality checks..."
- npm ci --prefer-offline --no-audit
- npm run lint
- npm run format:check
- echo "✅ Code quality checks passed!"
cache:
key:
files:
- package-lock.json
paths:
- node_modules/
- .npm/
only:
- merge_requests
- develop
- main
# Job 2: Validate Commit Messages
lint:commit:
stage: lint
variables:
GIT_DEPTH: 0 # Fetch full git history for commit range
before_script:
- npm ci --prefer-offline --no-audit
script:
- echo "Validating commit messages..."
- npx commitlint --from ${CI_MERGE_REQUEST_DIFF_BASE_SHA} --to ${CI_COMMIT_SHA} --verbose
- echo "✅ All commit messages follow conventional format!"
cache:
key:
files:
- package-lock.json
paths:
- node_modules/
- .npm/
only:
- merge_requests # Only validate commits in merge requests
# ... rest of your pipeline ...lint:code runs on MRs (merge requests) and protected branches. It runs the ESLint and Prettier checks. If it fails, the merge is blocked.
lint:commit runs on MRs only. It checks all commit messages in the MR range.
Does someone skip the hooks with --no-verify? CI still catches it.
Step 9: Team Onboarding#
It is automatic.
For New Team Members#
# 1. Clone repository
git clone https://gitlab.stack101.dev/your-org/blog.stack101.git
# 2. Install dependencies
npm install
# That's it! Hooks are installed automatically via prepare scriptnpm install starts prepare, which runs husky install. That is all.
What to Tell Your Team#
Share this in your team docs:
## Git Hooks Are Enabled
This project uses Husky for automated code quality checks.
**What happens when you commit:**
- Pre-commit: Lints and formats your staged files (2-3 seconds)
- Commit-msg: Validates your commit message format
**Commit message format:**
```bash
<type>: <subject>
[optional body]
```Valid types: feat, fix, docs, style, refactor, test, chore, ci, build
Examples:
- ✅
feat: add user dashboard - ✅
fix: resolve login timeout issue - ✅
docs: update README with setup instructions - ❌
Fixed bug(missing type) - ❌
FEAT: Add Feature(subject must be lowercase)
If hooks fail:
- Fix the reported errors
- Stage your fixes:
git add . - Try committing again
To skip hooks (emergency only):
git commit --no-verify -m "emergency: hotfix for production"CI/CD still runs all checks. So when you skip the hooks, your code is still checked.
Results & Benefits#
Before Hooks#
git commit -m "fixed stuff"
git push origin feature/my-feature
# Wait 3-5 minutes for CI...
# CI fails: "ESLint errors found"
# Fix errors locally
# Push again
# Wait another 3-5 minutes...Time lost: 6-10 minutes per cycle.
After Hooks#
git commit -m "fixed stuff"
# ❌ Hook fails in 2 seconds: "Invalid commit format"
git commit -m "fix: resolve user authentication bug"
# ✅ Hook passes in 3 seconds
# ✅ CI passes on first try (because hooks caught issues)Time saved: 6-10 minutes per commit that would have failed CI.
Next Steps#
The hooks work. Here is what you can add next.
1. Pre-Push Hook (Optional)#
Run slower checks before you push:
"npm test"This runs your full test suite before the code reaches the remote.
2. Custom Validation Rules#
Add checks that only your project needs to .husky/pre-commit:
# Check for console.log in production code
if git diff --cached | grep -E "console\.(log|warn|error)" >/dev/null 2>&1; then
echo "❌ Found console statements. Remove them before committing."
exit 1
fi
npx lint-staged3. Monitor Hook Performance#
Measure how long the hook takes:
# Add to pre-commit
start_time=$(date +%s)
npx lint-staged
end_time=$(date +%s)
echo "⏱️ Lint-staged took $((end_time - start_time)) seconds"If the hooks often take more than 5 seconds, make your linting patterns faster.
Conclusion#
You now have Git hooks that are ready for production. They:
- Catch linting errors on your computer in < 5 seconds
- Keep commit messages in one format
- Work together with the GitLab CI/CD pipeline
- Install themselves for new team members
- Can be changed and extended as you like
Main points:
- Hooks save time because they catch errors before CI/CD
- Lint-staged keeps hooks fast (staged files only)
- Husky lets you share hooks with the team
- CI/CD stays as the backup
Related reading:
- Git Hooks for Automation - Theory, patterns, and advanced hooks
- Git Branching Strategy: A Practical Case - The full workflow around it
- How to Fix: Accidentally Committed to Main Branch - Recover from common mistakes