Pre-commit tools catch formatting errors, lint failures, fragile tests, and accidental secrets before a change reaches a shared repository. This guide compares the main approaches and provides practical setup patterns for JavaScript, Python, Go, and mixed-language projects.
Overview
A pre-commit hook is a local Git action that runs before Git creates a commit. Used well, it gives developers fast feedback at the point where a mistake is introduced. It is not a replacement for continuous integration: local hooks can be skipped, environments can differ, and expensive integration tests may not belong on every commit. The most reliable workflow uses hooks for quick, deterministic checks and CI for the complete policy.
The best choice depends on how much orchestration your repository needs. A framework such as pre-commit provides a language-independent configuration model and reusable hooks. Husky integrates naturally with Node.js projects by managing Git hooks through package scripts. Lefthook is a fast, multi-language runner with a central configuration file. lint-staged focuses on running commands only against staged files and is commonly paired with Husky. Language-specific hooks, such as a formatter, linter, or test runner supplied by a language ecosystem, offer a smaller setup when one stack dominates the repository.
| Tool or approach | Ecosystems | Typical setup | Staged-file handling | Formatting and linting | Tests | Secret scanning | Speed and CI fit |
|---|---|---|---|---|---|---|---|
| pre-commit | Multi-language | .pre-commit-config.yaml | Hook framework passes relevant files to configured hooks | Strong through configured formatters and linters | Possible, but keep slow suites out of the default path | Through a configured secret-scanning hook | Good for repeatable local checks; easy to mirror in CI |
| Husky | Especially JavaScript and Node.js | Git hook files plus package.json scripts | Delegates selection to commands or tools such as lint-staged | Uses the project’s existing npm or package-manager commands | Runs any script you explicitly attach | Requires a separate scanner or script | Lightweight hook manager; CI runs the same scripts independently |
| Lefthook | Multi-language | lefthook.yml or equivalent project configuration | Supports file patterns and staged-file workflows | Commands and file filters are configured centrally | Supports dedicated commands, groups, and hook stages | Requires a configured scanner | Designed for parallel or selective checks; CI can invoke the same commands |
| lint-staged | Common in JavaScript projects | package.json or a lint-staged configuration file | Its core purpose is running commands on staged files | Excellent for formatters and linters that rewrite or inspect files | Possible, although tests often need broader project context | Can run a scanner against staged paths | Fast when paired with a hook manager; CI needs a separate full-check command |
| Language-specific hooks | One language or framework | Tool-specific configuration and package scripts | Varies; some tools inspect changed files, others inspect the project | Usually strongest for that language | Usually easiest to connect to the native test runner | Usually external | Minimal moving parts; mixed repositories may need several systems |
Secret scanning deserves separate attention. Formatting and linting are usually deterministic and local. A secret scanner may need repository history, ignore rules, baseline management, or careful treatment of generated files. Configure it deliberately, and keep the authoritative scan in CI or another protected environment rather than relying only on a developer’s laptop.
Checklist by scenario
JavaScript or TypeScript
- Choose one hook manager, such as Husky or Lefthook, rather than installing overlapping managers.
- Use lint-staged when formatters and linters should receive only staged files.
- Keep package scripts reusable so developers and CI call the same commands.
- Run type checking and the broader test suite in CI unless the repository is small enough for them to remain fast locally.
# Example package scripts
{
"scripts": {
"format:check": "prettier --check .",
"lint": "eslint .",
"test": "your-test-runner",
"typecheck": "tsc --noEmit",
"prepare": "husky"
},
"lint-staged": {
"*.{js,jsx,ts,tsx}": ["prettier --write", "eslint --fix"]
}
}
Attach the staged-file command to the pre-commit hook, then define a separate CI command that runs format:check, lint, typecheck, and tests across the repository.
Python
- Use a language-independent runner if the repository also contains documentation, shell scripts, or frontend code.
- Configure the formatter and linter with the project’s chosen line length, exclusions, and target Python version.
- Run focused tests locally only when they are quick and stable.
- Make the virtual environment or tool installation procedure explicit for new contributors.
# Example .pre-commit-config.yaml structure
repos:
- repo: https://example.invalid/formatter-hook
rev: <reviewed-version>
hooks:
- id: formatter
- id: linter
- repo: local
hooks:
- id: unit-tests
name: focused unit tests
entry: python -m pytest tests/unit
language: system
pass_filenames: false
stages: [pre-commit]
Replace the placeholder repository and revision with the hooks your team has reviewed. The important design choices are explicit exclusions, reproducible versions, and a test command that does not accidentally run an entire slow suite on every commit.
Go
- Format Go files automatically before committing, then verify that formatting leaves no unexpected diff.
- Run fast static checks and package-level tests locally.
- Keep integration tests, race-heavy checks, and platform-specific tests in CI unless they are proven fast on developer machines.
- Include generated-code rules so hooks do not rewrite files that should be produced by a generator.
# Example Lefthook-style command structure
pre-commit:
parallel: true
commands:
gofmt:
glob: "**/*.go"
run: gofmt -w {staged_files}
go-test:
glob: "**/*.go"
run: go test ./...
stage_fixed: true
Test the exact placeholder syntax supported by the selected runner before adopting this configuration. Some teams prefer a dedicated script that formats files, stages the result, and then runs checks; the essential requirement is that the final committed content is the content that was checked.
Mixed-language repositories
- Use one top-level orchestrator when possible, with file globs that prevent irrelevant tools from running.
- Give each language its own script and documented runtime requirements.
- Run repository-wide checks in CI even when local hooks select only changed files.
- Add secret scanning, documentation checks, and infrastructure validation as separate named commands.
A central configuration is easier to explain during onboarding. However, a small repository may be better served by native package scripts and a simple hook. Prefer the smallest system that enforces the checks you actually need.
What to double-check
- Reproducibility: Pin or otherwise review hook versions, formatter versions, and runtime versions. Confirm how updates are tested before changing them.
- File selection: Check whether a command receives staged files, all changed files, or the entire repository. This affects both speed and correctness.
- Auto-fixing: If a formatter changes files, decide whether the hook stages those changes automatically or stops so the developer can review them.
- CI parity: List the local commands and their CI equivalents. A local hook should provide early feedback, not create a second, contradictory policy.
- Operating systems: Test shells, path handling, executable permissions, line endings, and runtime discovery on Windows, macOS, and Linux where applicable.
- Secret handling: Confirm that scanners ignore approved fixtures without hiding real credentials. Never place real secrets in test data merely to verify a hook.
- Bypass policy: Decide how an emergency bypass is recorded and ensure CI still blocks unsafe code. A bypass should be exceptional, not a routine way to reduce friction.
Common mistakes
The most common failure is putting too much work in the pre-commit path. A hook that takes several minutes will be disabled or bypassed. Start with formatting, targeted linting, and a small test set; move broad tests and heavyweight analysis to pre-push or CI.
Another mistake is combining multiple hook managers. Choose one owner for each Git hook, and make installation part of the documented project setup. Also avoid commands that inspect only the staged version while reading unstaged files or generated artifacts from the working tree; the result can be confusing and inconsistent.
Finally, do not assume a successful local hook proves repository safety. Hooks can be skipped, removed, or run with different dependencies. Protect the shared branch with CI checks and make the local workflow a convenient first line of defense.
When to revisit
Review the hook workflow when starting a repository, adding a language, changing package managers, replacing a formatter or linter, introducing secret scanning, or reorganizing CI. Revisit it after major tool releases and at least twice yearly so configuration syntax, supported runtimes, installation commands, licensing, and integrations can be checked against current project needs.
Use this short review checklist:
- Measure the usual hook duration on a clean checkout and on a large change.
- Compare every local check with its CI counterpart and remove duplicated or contradictory commands.
- Test installation from the documented onboarding steps on each supported operating system.
- Make one intentional test commit with a formatting error, lint error, failing test, and safe secret fixture to verify expected behavior.
- Document the approved recovery path for a failed hook, including how to rerun it and how an exceptional bypass is handled.
The right pre-commit setup is not the one with the longest list of checks. It is the one developers can run consistently, understand quickly, and trust to match the quality gates protecting the shared repository.