Skip to content

Pre-commit Hook

In one line

A pre-commit hook is a script Git runs before creating a commit, able to reject the commit if checks fail.

In simple words

A pre-commit hook is a script in .git/hooks/pre-commit that Git runs right before a commit is finalized. If the script exits with a non-zero status, the commit is aborted. This lets you block bad commits at the source — before they ever reach the shared history.

Common checks: linting (eslint, ruff), formatting (prettier, black), type-checking, secret scanning (no API keys committed), and running a fast subset of tests. The hook runs on the staged files, so it catches problems locally instead of in CI. Tools like pre-commit (the framework) and husky manage hooks across a team.

Hooks in .git/hooks are local and not committed, so teams use husky + lint-staged (in package.json) or the pre-commit framework (in .pre-commit-config.yaml) to share hook configuration. This ensures every contributor runs the same checks before committing.

Example

bash
# .git/hooks/pre-commit (must be executable)
#!/bin/sh
# Lint staged files; abort commit on failure

files=$(git diff --cached --name-only --filter=ACM | grep "\.js$")
if [ -n "$files" ]; then
  npx eslint $files || { echo "lint failed"; exit 1; }
fi

# With husky + lint-staged (package.json):
# "lint-staged": { "*.js": ["eslint --fix", "git add"] }

The hook lints staged .js files. If eslint fails, exit 1 aborts the commit. husky + lint-staged share this across the team.

Related terms

Related Resources

Related Lessons

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors

← Back to glossary