heydeer

Git hooks: pre-commit and pre-push with Husky or Lefthook

· · 10 min read

A git hook is the cheapest place to catch a problem: a formatting slip, a lint error or an API key gets stopped on the laptop that created it, seconds after it was written. The catch is that hooks live outside version control, so getting a whole team to run the same ones takes a hook manager such as Husky, Lefthook or the pre-commit framework.

Git hooks are executable scripts that Git runs automatically at points in its workflow, such as before a commit (pre-commit), after the commit message is written (commit-msg) or before a push (pre-push). They live in .git/hooks by default, a non-zero exit from a pre-hook stops the command, and because that directory isn’t cloned, teams share hooks through core.hooksPath or a manager such as Husky, Lefthook or pre-commit.

What git hooks are

Every repository has a .git/hooks directory. git init fills it with sample scripts that do nothing until you rename them:

$ ls .git/hooks
applypatch-msg.sample      pre-push.sample
commit-msg.sample          pre-rebase.sample
fsmonitor-watchman.sample  pre-receive.sample
post-update.sample         prepare-commit-msg.sample
pre-applypatch.sample      push-to-checkout.sample
pre-commit.sample          sendemail-validate.sample
pre-merge-commit.sample    update.sample

Drop the .sample suffix, make the file executable, and Git runs it at the matching moment. A hook can be written in any language with a shebang line; Git ignores files without the executable bit. Hooks run from the root of the working tree, and for the “pre” hooks a non-zero exit status cancels the command.

Hooks come in two groups. Client-side hooks run on the developer’s machine during commits, merges, rebases and pushes. Server-side hooks (pre-receive, update, post-receive) run on the server that receives a push and can reject it. GitHub.com and most hosted platforms don’t let you install server-side hooks; branch protection, rulesets and required status checks fill that role there.

The client-side hooks most teams use:

HookRunsCan stop the commandTypical use
pre-commitBefore Git asks for the commit messageYes; skipped by --no-verifyFormat and lint staged files, scan for secrets
prepare-commit-msgAfter the default message is prepared, before the editorYes; not skipped by --no-verifyInsert a ticket number from the branch name
commit-msgWith the path to the finished messageYes; skipped by --no-verifyEnforce Conventional Commits or a message format
post-commitAfter the commit is madeNoNotifications
pre-pushBefore objects are sent; refs arrive on stdinYes; skipped by git push --no-verifyType check, unit tests, block pushes to main
post-mergeAfter a successful merge, including git pullNoReinstall dependencies when the lockfile changed
post-checkoutAfter git checkout or git switch, and after git cloneNoRegenerate build files, clean caches
pre-rebaseBefore git rebase startsYesRefuse to rebase branches that are already published

How to write a pre-commit and a pre-push hook by hand

A hook manager is optional. Two short shell scripts already show how the whole mechanism works. This pre-commit hook lints only the files staged for the commit, which keeps it fast no matter how large the repository is:

#!/bin/sh
# .git/hooks/pre-commit
# Lint only the JavaScript and TypeScript files staged for this commit.
files=$(git diff --cached --name-only --diff-filter=ACM -- '*.js' '*.ts' '*.tsx')
[ -z "$files" ] && exit 0

npx eslint $files || {
  echo "ESLint found problems in staged files. Fix them, or commit with --no-verify."
  exit 1
}
chmod +x .git/hooks/pre-commit

git diff --cached lists what is staged, and --diff-filter=ACM keeps added, copied and modified files so deleted ones don’t reach ESLint. This simple version lints the file on disk rather than the staged snapshot, and file names with spaces would break the word splitting; the managers below solve both.

A pre-push hook gets more context. Git passes the remote’s name and URL as arguments and writes one line per ref to standard input, in the form <local-ref> <local-object-name> <remote-ref> <remote-object-name>. That makes it possible to block a direct push to main and then run the slower checks:

#!/bin/sh
# .git/hooks/pre-push
# $1 = remote name, $2 = remote URL; stdin has one line per ref being pushed:
# <local-ref> <local-object-name> <remote-ref> <remote-object-name>
while read local_ref local_oid remote_ref remote_oid; do
  if [ "$remote_ref" = "refs/heads/main" ]; then
    echo "Push to main through a pull request."
    exit 1
  fi
done

npm run typecheck && npm test

Why hooks aren’t shared on clone, and core.hooksPath

Nothing under .git/ is versioned, so git clone never copies hooks. That is deliberate: a hook is code that runs on your machine, and a repository that could install one silently would run arbitrary commands the moment you committed. Every developer has to opt in.

The built-in way to make opting in easy is core.hooksPath. Commit the scripts to an ordinary directory, then point Git at it:

mkdir -p .githooks
cp .git/hooks/pre-commit .git/hooks/pre-push .githooks/
git add .githooks && git commit -m "Share git hooks"

# Every clone runs this once:
git config core.hooksPath .githooks

Once core.hooksPath is set, Git reads hooks only from that directory and ignores .git/hooks. The weak spot is the last line: someone has to run it in each clone, and new teammates forget. Hook managers automate that step, usually by hooking into the package manager’s install, and add the parts plain scripts lack: staged file lists, parallel jobs and per-hook skipping.

Any of these hooks can be bypassed for a single command, which is useful for a work-in-progress commit:

git commit --no-verify -m "WIP"   # or: git commit -n
git push --no-verify

--no-verify skips pre-commit and commit-msg on a commit, and pre-push on a push. Because anyone can do this, a hook is a convenience for the author, never a gate. Anything that must hold for every merge has to run again in CI.

What belongs in pre-commit, pre-push and CI

The useful rule is to sort checks by how long they take and how much of the codebase they need. A pre-commit hook runs dozens of times a day, so if it takes more than a few seconds people start committing with --no-verify and the hook stops doing anything at all.

  • pre-commit: seconds, staged files only. Formatters (Prettier, Black, Ruff format, gofmt), linters with autofix on the staged files, whitespace and end-of-file fixers, and a secret scanner. Secrets matter most here, because a key that never enters history never needs rotating; the secret scanning tools guide compares Gitleaks, TruffleHog and the others.
  • commit-msg: instant. Message format checks such as commitlint.
  • pre-push: under a minute or two. Type checking, unit tests, a build of the changed package, and rules about which branches can be pushed.
  • CI: everything, every time. The full test suite, integration tests, static analysis across the repository, dependency audits and code review on the pull request. CI is the only layer nobody can skip. The static code analysis guide covers which analyzers belong there, and the GitHub Actions pricing guide what that costs in minutes.

With that split in mind, the three hook managers mostly differ in how they let you express it.

How to set up Husky pre-commit and pre-push hooks

Husky (version 9.1.7 as of November 2026) is the usual choice in JavaScript and TypeScript projects. Install it with lint-staged, which handles the staged-files part:

npm install --save-dev husky lint-staged
npx husky init

husky init creates a sample .husky/pre-commit script and sets the prepare script in package.json to husky. npm runs prepare after every install, and Husky then sets core.hooksPath to .husky/_, so a teammate gets the hooks just by running npm install. With pnpm or Bun, use pnpm exec husky init or bunx husky init. Edit the hooks into this shape:

# .husky/pre-commit
npx lint-staged

# .husky/pre-push
npm run typecheck
npm test
// package.json
{
  "scripts": {
    "prepare": "husky"
  },
  "lint-staged": {
    "*.{js,ts,tsx}": "eslint --fix",
    "*.{js,ts,tsx,css,md}": "prettier --write"
  }
}

Husky hooks are plain POSIX shell scripts, and Husky itself doesn’t look at files at all. lint-staged does that work: it backs up the current state, hides unstaged changes in partially staged files, runs each command on the matching staged files, adds the fixes to the commit and restores everything if a task fails. To turn Husky off for one command or a CI job, set HUSKY=0.

How to set up Lefthook

Lefthook, from Evil Martians, is a single Go binary (version 2.2.3 as of November 2026, MIT licensed), so the same tool works in a Node project, a Rails app or a Go service. It installs through npm, Homebrew, go install, pipx, gem and several system package managers:

npm install --save-dev lefthook   # also: brew, go install, pipx, gem
npx lefthook install

lefthook install writes small scripts into .git/hooks that call lefthook run <hook>. The npm package runs it on postinstall; with pnpm, add lefthook to onlyBuiltDependencies or that script is skipped. The whole setup lives in one file:

# lefthook.yml
pre-commit:
  parallel: true
  jobs:
    - name: eslint
      glob: "*.{js,ts,tsx}"
      run: npx eslint --fix {staged_files}
      stage_fixed: true
    - name: prettier
      glob: "*.{js,ts,tsx,css,md}"
      run: npx prettier --write {staged_files}
      stage_fixed: true
    - name: secrets
      run: gitleaks git --pre-commit --redact --staged --verbose

pre-push:
  parallel: true
  jobs:
    - name: typecheck
      run: npm run typecheck
    - name: test
      run: npm test

parallel: true runs the jobs of a hook at the same time. glob limits a job to matching files, {staged_files} passes only the staged ones ({push_files} gives the committed but unpushed files in a pre-push job, {all_files} every tracked file), and stage_fixed: true re-stages whatever the formatter changed. Developers can override or add jobs for themselves in a lefthook-local.yml that stays out of git, and turn Lefthook off for one command:

LEFTHOOK=0 git commit -m "WIP"

Most “Lefthook vs Husky” comparisons come down to this file. Husky gives you shell scripts and leaves file selection to lint-staged; Lefthook puts globs, staged-file templates and parallelism into the config, which pays off in monorepos and mixed-language repositories.

How to set up the pre-commit framework

The pre-commit framework (pre-commit.com) is the default in Python projects, but it runs hooks written in any language. Each hook comes from a repository pinned to a tag, and pre-commit builds an isolated environment for it, so a teammate doesn’t need Ruff or Gitleaks installed beforehand.

# .pre-commit-config.yaml
default_install_hook_types: [pre-commit, pre-push]
repos:
  - repo: https://github.com/pre-commit/pre-commit-hooks
    rev: v6.0.0
    hooks:
      - id: trailing-whitespace
      - id: end-of-file-fixer
      - id: check-yaml
  - repo: https://github.com/astral-sh/ruff-pre-commit
    rev: v0.17.6
    hooks:
      - id: ruff-check
        args: [--fix]
      - id: ruff-format
  - repo: https://github.com/gitleaks/gitleaks
    rev: v8.30.1
    hooks:
      - id: gitleaks
  - repo: local
    hooks:
      - id: pytest
        name: pytest
        entry: pytest -q
        language: system
        pass_filenames: false
        stages: [pre-push]
pip install pre-commit
pre-commit install            # installs the hook types listed above
pre-commit run --all-files    # run every hook once on the whole repository
pre-commit autoupdate         # bump each rev to the latest tag
SKIP=pytest git push          # skip one hook by id

pre-commit runs only on the staged contents of files: it temporarily stashes unstaged changes, runs the hooks, and puts them back. default_install_hook_types makes a single pre-commit install set up both hook types, and a hook with stages: [pre-push] runs only on push. Run pre-commit run --all-files once after adding a hook, and again in CI, so the rules apply to code that was committed before the hook existed.

Husky vs Lefthook vs pre-commit compared

ManagerLanguage and packagingConfigParallel jobsStaged filesInstall for teammates
Husky (v9)Node.js package; hooks are POSIX shell scriptsOne shell file per hook in .husky/Whatever the script does; usually sequentialThrough lint-staged, which runs tasks on staged files and re-stages fixesnpm install, then the prepare script sets core.hooksPath to .husky/_
LefthookSingle Go binary; npm, Homebrew, Go, pipx and gem packageslefthook.yml (also TOML or JSON), plus personal lefthook-local.ymlparallel: true per hook{staged_files} and {push_files} templates, glob filters, stage_fixedlefthook install (the npm package runs it on postinstall)
pre-commit frameworkPython tool; hooks in any language, each in its own environment.pre-commit-config.yaml with pinned repo revisionsRuns a hook’s files in parallel processes unless require_serialStashes unstaged changes, so hooks see only what will be committedpip install pre-commit, then pre-commit install

A JavaScript repository with a handful of checks is well served by Husky and lint-staged. A monorepo, or a team that wants one config for several languages and speed from parallel jobs, tends to pick Lefthook. A Python codebase, or one that wants every hook pinned to a version and installed in its own environment, fits the pre-commit framework. All three can run the same Gitleaks hook.

Where AI code review fits next to git hooks

AI review sits at the other end of the timeline from a formatter. A useful review reads the whole change against what it was meant to do, which takes minutes rather than seconds, so it belongs at the point where a branch is ready to become a pull request, not on every commit. The AI code review guide covers what that kind of review catches that hooks and linters don’t.

HeyDeer reviews GitHub pull requests, and its CLI runs the same review on a local branch first. heydeer review takes a description of what the change is meant to do and reviews the branch’s commits plus uncommitted changes to tracked files against the default branch, verifying each finding before it reports it. Fix what you agree with and run it again: the next review covers what changed since the last one and rechecks the open findings. Then push.

git switch retry-uploads
heydeer review "Retry failed uploads up to three times. Fixes #123."
# fix what you agree with, then
heydeer review "Retry failed uploads up to three times. Fixes #123."
git push -u origin retry-uploads

For a developer who wants the review tied to git push, a personal, opt-in pre-push job keeps it out of everyone else’s workflow. A finished review exits with 0 whether or not it has findings, so this job prints the findings and lets the push go ahead; scripts that need to decide pass --json and read the findings from the output.

# lefthook-local.yml — listed in your global .gitignore, so only you run it
pre-push:
  jobs:
    - name: heydeer
      run: heydeer review --description-file .git/pr-description.md

Coding agents can take the same step. An instruction in AGENTS.md to run heydeer review --json before opening a pull request has Claude Code, Codex or Cursor review and fix its own branch; the CLI docs list every option.

Sources

  1. Git documentation: githooks
  2. Git documentation: git push (--no-verify)
  3. Pro Git: Customizing Git - Git Hooks
  4. Husky: Get started
  5. Husky: How to
  6. Husky source: index.js
  7. lint-staged: README
  8. Lefthook documentation
  9. Lefthook: run option and templates
  10. Lefthook: install with Node.js
  11. Lefthook: environment variables
  12. evilmartians/lefthook: README
  13. pre-commit framework documentation
  14. Gitleaks: pre-commit hooks
  15. Ruff: pre-commit hook

Frequently asked questions

What is a Git hook?

A Git hook is a script Git runs automatically when a particular event happens, such as a commit, a merge or a push. Client-side hooks like pre-commit, commit-msg and pre-push run on a developer’s machine and can stop the command by exiting with a non-zero status; server-side hooks like pre-receive run on the server that receives a push.

What is Lefthook used for?

Lefthook is a Git hooks manager from Evil Martians, written in Go, that installs and runs hooks defined in a lefthook.yml file committed to the repository. It is used to run linters, formatters, secret scanners and tests on commit or push, with jobs that can run in parallel and receive only the staged or pushed files.

How do I install Lefthook?

Lefthook installs as a dev dependency with npm install --save-dev lefthook, or as a standalone binary through Homebrew, go install, pipx or gem. After adding a lefthook.yml file, run lefthook install to write the hooks into .git/hooks; the npm package does this on postinstall, though pnpm needs lefthook listed in onlyBuiltDependencies first.

What is Husky used for?

Husky is an npm package that makes Git hooks part of a JavaScript project. It keeps hook scripts in a committed .husky directory and, through the prepare script that runs on npm install, points core.hooksPath at it, so every developer who installs dependencies gets the same pre-commit and pre-push hooks.

Lefthook vs Husky: which should I use?

Lefthook and Husky both share git hooks across a team. Husky suits a JavaScript project that is happy with plain shell scripts, usually paired with lint-staged for staged files. Lefthook suits monorepos and mixed-language repositories, since it is a single binary with YAML config, built-in parallel jobs and staged-file templates.

How do I skip a pre-commit hook?

A pre-commit hook is skipped with git commit --no-verify (or -n), which bypasses both pre-commit and commit-msg; git push --no-verify skips pre-push. Hook managers add finer controls: HUSKY=0 disables Husky, LEFTHOOK=0 disables Lefthook, and SKIP=hook-id skips individual hooks in the pre-commit framework.

Should tests run in a pre-commit or pre-push hook?

Tests usually belong in a pre-push hook rather than pre-commit. A pre-commit hook runs on every commit, so it should finish in seconds with checks on staged files such as formatting, linting and secret scanning. A pre-push hook runs less often and can afford a type check and the unit tests, while CI runs the full suite.

Start with your first PR.

Free plan. No credit card required.

Get started free