Skip to content

Husky - Git Hooks Made Easy

NPM Last Update NPM Downloads NPM Version

Husky is a tool that makes Git hooks easy to use and manage. It allows you to run scripts automatically before commits, pushes, and other Git operations, helping you enforce code quality, run tests, and maintain consistent standards across your team.


Install husky via npm, yarn, or pnpm:

Terminal window
npm install --save-dev husky
# or
yarn add --dev husky
# or
pnpm add --save-dev husky

Terminal window
npx husky init

This creates a .husky directory with a sample pre-commit hook.

Add a pre-commit hook to run linting:

Terminal window
echo "npm run lint" > .husky/pre-commit

Add helpful scripts to your package.json:

{
"scripts": {
"prepare": "husky",
"lint": "eslint .",
"test": "vitest run"
}
}

Create different hooks for different Git operations:

Terminal window
# Pre-commit: lint and format
echo "npm run lint && npm run format" > .husky/pre-commit
# Pre-push: run tests
echo "npm test" > .husky/pre-push
# Commit-msg: validate commit message
echo "npx commitlint --edit $1" > .husky/commit-msg

Sometimes you need to skip hooks:

Terminal window
git commit --no-verify -m "emergency fix"

Combine Husky with lint-staged for optimal performance:

Terminal window
npm install --save-dev lint-staged

Add to package.json:

{
"lint-staged": {
"*.{js,jsx,ts,tsx}": ["eslint --fix", "prettier --write"],
"*.{json,md}": ["prettier --write"]
}
}

Update .husky/pre-commit:

Terminal window
npx lint-staged

Create more complex hooks with shell scripts:

#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
# Run type checking
npm run type-check || exit 1
# Run tests for changed files
npm run test:changed || exit 1
echo "✅ All checks passed!"

  • Keep Hooks Fast: Only run checks on staged files to avoid slowing down commits
  • Use lint-staged: Process only changed files for better performance
  • Document Your Hooks: Add comments explaining what each hook does
  • Team Alignment: Ensure all team members understand and agree on hook policies
  • Graceful Failures: Provide clear error messages when hooks fail
  • CI/CD Integration: Run the same checks in your CI pipeline as backup

.husky/pre-commit
npm run lint
npm run format:check
npm run type-check
.husky/commit-msg
npx commitlint --edit $1
.husky/pre-push
npm run test:coverage
.husky/post-merge
npm install

For more details, check out the Husky official documentation.