Build a dependable local quality gate with Git pre-commit hooks that format staged files, run focused lint checks, execute appropriate tests, and detect accidental secrets before changes enter your repository.
Overview
Pre-commit automation moves repeatable checks closer to the moment a developer creates a commit. Instead of relying on memory or waiting for CI to report an avoidable formatting error, a hook can inspect the proposed change and stop the commit when a required check fails.
A useful workflow separates fast local checks from broader CI validation. Local hooks should usually handle inexpensive operations such as formatting, linting staged files, type checks for small projects, focused unit tests, and basic secret detection. CI should remain the final authority for the complete test suite, production builds, dependency audits, integration tests, and checks that require a clean, controlled environment.
For JavaScript and TypeScript projects, a common arrangement is:
- Git identifies a commit attempt.
- A pre-commit hook invokes a staged-file runner.
- The runner passes only staged files to formatters and linters.
- Fast tests or affected tests run when the change justifies them.
- The commit proceeds only if the required commands succeed.
- CI repeats the important checks independently rather than trusting a local hook.
Keep secrets out of command output and configuration. A hook can reduce accidental exposure, but it is not a substitute for secret management, repository access controls, or a response plan if a credential is already committed. For related validation work, compare this process with an API testing workflow and an OpenAPI validation workflow.
Tool comparison
| Option | Best fit | Strength | Trade-off |
|---|---|---|---|
| Native Git hooks | Small or tightly controlled repositories | No extra hook manager is required | Installation, portability, and executable permissions are your responsibility |
| Husky | JavaScript and Node.js repositories | Convenient project-level hooks integrated with package scripts | Setup behavior can vary by release and package-manager configuration |
| Lefthook | Teams wanting a centralized, configurable hook runner | Supports multiple hooks and parallel command configuration | Adds another tool and configuration format to maintain |
| lint-staged | Projects that should process only staged files | Reduces unnecessary work and limits commands to the proposed change | It is a staged-file runner, not a complete hook installation system |
| pre-commit | Polyglot repositories and teams using declarative hook configuration | Works across many languages and can standardize reusable checks | Requires its own runtime and configuration conventions |
These tools can be combined. For example, Husky or Lefthook can install and invoke the Git hook while lint-staged selects the files to process. Choose the smallest combination that your team can explain, install, and troubleshoot.
Checklist by scenario
Scenario 1: Starting a JavaScript or TypeScript repository
- Define the checks first. Decide which commands are fast enough for every commit. Typical examples are a formatter in check or write mode, a linter, and a focused test command.
- Make the commands work without Git hooks. Add scripts such as
format,format:check,lint,typecheck, andtest:unitto the project configuration. Run each command directly before wiring automation. - Install a hook manager and staged-file runner. A representative npm setup is
npm install --save-dev husky lint-staged. Use the equivalent command for your package manager, and confirm the supported Node.js runtime in the tool documentation before standardizing the setup. - Enable installation for contributors. Configure the package lifecycle or repository setup so hooks are installed after a normal dependency install. Review this behavior carefully in CI, containers, and production installs where development dependencies may be omitted.
- Create a staged-file rule. A typical configuration maps file patterns to commands, for example
*.{js,jsx,ts,tsx}to a formatter followed by a linter, and*.{json,md,css}to the formatter. Prefer commands that receive file paths rather than scanning the entire repository. - Add the pre-commit entry point. The hook should call the staged-file runner and exit with its status. A failed formatter, linter, or test must return a non-zero status so Git stops the commit.
- Test the complete path. Modify one supported file, stage it, run the commit, and inspect whether the formatter changes the index or leaves unstaged edits. Then introduce a deliberate lint error and verify that the commit is blocked.
Scenario 2: Adding tests without making commits painful
- Run unit tests related to changed files when your test runner supports reliable file filtering.
- Keep integration, browser, migration, and full-build checks in CI unless the repository is small enough for local execution.
- Document a fast escape route for debugging, but require the bypass to be visible and explainable.
- Ensure test commands do not depend on an unavailable database, service, port, or operating-system utility during ordinary commits.
Scenario 3: Adding secret checks
- Scan staged content rather than only the working tree, because the commit is the boundary being protected.
- Exclude generated files only when the exclusion is understood and documented. An overly broad ignore rule can hide a real credential.
- Use placeholder credentials in tests and examples. Do not place real tokens in hook configuration, test fixtures, or command arguments.
- Send the same or stronger secret-detection policy to CI. A local hook can be bypassed with
git commit --no-verify, and hooks do not protect commits created elsewhere.
Scenario 4: Supporting a mixed-language repository
Use a tool that can dispatch commands by file type, or keep separate hook commands for each application area. A Python service, JavaScript frontend, infrastructure directory, and documentation folder should not all receive the same formatter or test command. A declarative configuration such as .pre-commit-config.yaml may be useful when the repository needs language-specific hooks and consistent onboarding.
Scenario 5: Working with a monorepo
- Identify the package owning each staged file.
- Run the narrowest affected lint and test commands first.
- Use repository-wide checks in CI or on demand rather than blocking every small commit with a full build.
- Test changes to root configuration separately, because they may affect every package.
What to double-check
Staged versus unstaged behavior: Confirm whether formatters update files in the working tree, the index, or both. After a hook runs, use git status and git diff --cached to verify that the commit contains the intended result.
Executable permissions: A hook file must be executable on systems that enforce Unix permissions. Check its mode in version control and test a fresh clone rather than relying only on the machine where it was created.
Package-manager consistency: Do not mix lockfiles or assume that npm, pnpm, Yarn, and other package managers execute lifecycle scripts identically. Document the supported install command and ensure the hook setup works in the package manager used by CI.
Runtime availability: Hooks may run from a different shell, path, or Node.js version than an interactive terminal. Avoid relying on aliases. If a command needs a specific runtime, make that requirement explicit and test it in a clean environment.
Hook bypasses: Treat --no-verify as an exceptional debugging option, not a normal workflow. CI must repeat critical checks because any developer or automation process can skip local hooks.
Performance: Measure the slowest normal commit path. Process staged files where possible, avoid rebuilding unrelated packages, and move expensive checks to a pre-push hook or CI when they do not provide useful commit-time feedback.
Failure messages: A blocked commit should tell the developer which command failed and what to run next. Avoid hiding the original tool output behind a generic “hook failed” message.
When checks involve generated files, SQL, or API contracts, define whether developers should format the source, the generated output, or both. A formatting workflow should improve readability without changing query logic; the SQL formatter guide provides a useful example of that distinction.
Common mistakes
- Installing a hook that is not committed. If setup files are ignored or created manually in a local Git directory, new contributors will not receive the same checks.
- Running the entire repository on every commit. This creates slow feedback and encourages bypasses. Start with staged files and focused tests.
- Formatting after linting without a second check. Formatting can alter code in ways that affect lint results. Order commands deliberately, or use a combined command that verifies the final state.
- Assuming a local pass proves CI will pass. Local environments differ in operating system, runtime, services, environment variables, and dependency installation mode.
- Making the hook depend on network access. A commit should not unexpectedly fail because a remote service or package registry is unavailable. Keep network-dependent validation in a controlled pipeline where practical.
- Logging sensitive values. Review command flags and failure output so tokens, connection strings, and environment variables are not printed.
- Skipping onboarding documentation. Add a short section to the README explaining installation, expected commands, common failures, and the approved exception process.
- Changing checks without checking CI parity. When a lint rule, formatter, runtime, or test command changes, update local hooks and CI together.
When to revisit
Review the pre-commit workflow before a new project begins, during seasonal planning cycles, and whenever the repository's inputs change. A practical maintenance checklist is:
- Confirm hook-manager and staged-runner commands against the versions recorded in the lockfile and the tools' current documentation.
- Test a clean clone with the supported package manager and runtime.
- Compare local scripts with CI scripts and remove duplicated logic where a shared command can be used.
- Measure hook duration after adding a formatter, linter, test suite, or secret scanner.
- Review bypass usage and investigate repeated failures rather than simply loosening the gate.
- Recheck secret patterns, generated-file exclusions, and repository ignore rules after adding new applications or deployment files.
- Update onboarding instructions when the install command, hook location, runtime, or configuration format changes.
Start with one reliable gate: format and lint staged files, return clear failures, and repeat the important checks in CI. Once that path is stable, add focused tests and secret detection one at a time. This incremental approach makes it easier to identify whether a failure comes from Git, the hook manager, the file selector, the command itself, or the surrounding environment. Revisit the checklist whenever workflows or tools change, and keep the local quality gate fast enough that developers trust it rather than work around it.