Back to results for “Testing with Jest”
Node.js › Git & Project Management

How would you use Git hooks (like a pre-commit hook via Husky) to enforce code quality checks before code is committed in a Node.js project?

Advanced

Answer

Git hooks are scripts that run automatically at specific points in the Git workflow (before a commit, before a push) -- Husky is a popular tool that makes configuring these hooks straightforward within a Node.js project's package.json, commonly used to run a linter, formatter, or a fast subset of tests against only the staged files before allowing a commit to proceed, catching basic issues locally before they ever reach a shared branch or CI.
// package.json
"husky": { "hooks": { "pre-commit": "lint-staged" } },
"lint-staged": { "*.js": ["eslint --fix", "prettier --write"] }

// This automatically lints and formats only the files being committed,
// before the commit is actually allowed to complete
Real-world example A team configures Husky and lint-staged to automatically run ESLint and Prettier on only the files being committed, catching style violations and simple bugs locally before a developer even pushes, rather than discovering them later in a CI pipeline or code review.

Common follow-ups: Why does lint-staged specifically run checks only against staged files rather than the entire codebase on every commit?;What's the risk of a pre-commit hook that takes too long to run, and how do teams balance thoroughness against developer friction?