toolsPractical setup for Husky + Commitlint pre-commit hooks

Husky and Commitlint:A useful pre-commit hook

Use Husky to run quick pre-commit checks via `lint-staged`, and Commitlint to validate commit messages with a `commit-msg` hook.

Husky and Commitlint are a compact, reliable combo for keeping Git histories tidy. Husky wires Git hooks into your npm scripts, and Commitlint enforces commit-message conventions.

This short guide shows a pragmatic setup: use Husky to run lint-staged in a pre-commit hook for code quality, and run Commitlint in a commit-msg hook to validate commit messages.

Install the tools

Install
npm install --save-dev husky lint-staged @commitlint/config-conventional @commitlint/cli

Husky setup

package.json (prepare)
{ "scripts": { "prepare": "husky install" } }
Add hooks
npx husky install npx husky add .husky/pre-commit "npx --no -- lint-staged" npx husky add .husky/commit-msg "npx --no -- commitlint --edit $1"

Commitlint config

commitlint.config.cjs
module.exports = { extends: ['@commitlint/config-conventional'], };

Lint-staged example

package.json (lint-staged)
{ "lint-staged": { "src/**/*.{js,ts,jsx,tsx}": [ "eslint --fix", "prettier --write", "git add" ], "src/**/*.{css,md}": [ "prettier --write", "git add" ] } }

Example commit message

A passing Conventional Commit looks like:

feat(auth): add OAuth2 redirect support Adds a new redirect handler and tests for OAuth2 flows.

The commit-msg hook will reject messages that do not follow the configured rules.

Troubleshooting

If hooks don't run after clone, run npm run prepare or npx husky install. CI should also run commitlint and linters to be safe.