You've just pushed, and five minutes later a teammate asks: "Why is there a console.log("test 123") in the production code?" Production code is the code that real users run. That line is a leftover from debugging (looking for the cause of a bug) that you forgot to delete. Git itself can check for a line like that, every time, before the commit is made.
A Git hook is a script that Git runs on its own at a certain moment, for example right before a commit is made. If the script fails, Git cancels that step. It's like the bag check at a mall entrance: before you go in, security takes a look. Pass, and you go in. Fail, and you don't get in, and nobody inside records that you came. In Git, the security guard is the hook, and getting into the mall is the commit being made.
Where hooks live
Every repo has a .git/hooks/ folder. On git init, Git fills it with example files like pre-commit.sample and commit-msg.sample. Those examples aren't active. For a hook to run and do its job, three things must be true:
- The file is named exactly after the hook, with no extension (the end of a file name, like
.sh):.git/hooks/pre-commit, notpre-commit.sh. - The file is executable (allowed to run as a program), and
chmod +x .git/hooks/pre-commitgives it that permission. - The exit code decides the result:
exit 0means carry on, any other number (for exampleexit 1) means Git cancels the step.
Your first hook: pre-commit
pre-commit runs when you type git commit, before the commit is made. The example below refuses the commit if app.js still holds a leftover debugging console.log:
#!/bin/sh
# .git/hooks/pre-commit
if grep -q "console.log" app.js; then
echo "pre-commit: app.js still has a console.log, remove it first"
exit 1
fi
echo "pre-commit: all clear"
#!/bin/shon the first line tells the system this file is a shell script, a script of terminal commands.grep -q "console.log" app.jslooks for that text inapp.js.-qmeans quiet: grep prints nothing, it only reports whether the text was found.- If it's found, the lines between
thenandfirun: the script prints the reason, then stops withexit 1. - If it's not found, the script prints
pre-commit: all clearand finishes with exit code 0.
Save that script as .git/hooks/pre-commit, give it permission with chmod +x, then try a commit:
$ chmod +x .git/hooks/pre-commit
$ git add app.js
$ git commit -m "feat: export the total function"
pre-commit: app.js still has a console.log, remove it first
$ git log --oneline
4e1d2a9 (HEAD -> main) chore: initial setup
The commit is cancelled completely. There's no new commit, git log still has one line, and Git adds no message of its own beyond what the hook printed. Delete the console.log line, git add app.js again, then commit again: the hook prints pre-commit: all clear and the commit is made.
Checking the commit message: commit-msg
commit-msg runs after the commit message is written. Git gives it one argument (a value passed to the script), $1: the location of the file holding that message. The example below requires the message to start with feat:, fix:, docs: or chore:.
#!/bin/sh
# .git/hooks/commit-msg
if ! grep -qE "^(feat|fix|docs|chore): " "$1"; then
echo "commit-msg: start the message with feat:, fix:, docs: or chore:"
exit 1
fi
The ! reverses grep's result, so exit 1 runs when the message doesn't start with one of those words. Here is what happens when the message is only update:
$ git commit -m "update"
pre-commit: all clear
commit-msg: start the message with feat:, fix:, docs: or chore:
The order: pre-commit first, then commit-msg, and only then is the commit made. If pre-commit has already failed, commit-msg doesn't run.
Client-side and server-side
Some hooks run on the developer's computer, and some run on the server that receives pushes. In the table, lint means checking code automatically, and deploy means installing a new version for users.
| Hook | Where it runs | When | Typical use |
|---|---|---|---|
pre-commit |
the developer's computer (client-side) | before the commit is made | lint, format, quick tests |
commit-msg |
the developer's computer (client-side) | after the message is written | check the message format |
pre-push |
the developer's computer (client-side) | before git push sends anything |
the full test suite |
pre-receive |
the server (server-side) | when a push arrives, before it's accepted | reject pushes that break the rules |
post-receive |
the server (server-side) | after a push is accepted | deploy, send a notification |
So pre-commit is client-side: it runs on your own computer, before anything is sent anywhere.
Sharing hooks with the team: Husky
What's inside the .git/ folder is never committed, so a hook in .git/hooks/ exists only on your computer. A teammate who clones your repo doesn't get it. Husky, a tool for JavaScript projects, moves the hooks to a normal folder, .husky/, which is committed. You install Husky with npm (a program that installs JavaScript tools):
$ npm install --save-dev husky
$ npx husky init
npx husky initcreates the file.husky/pre-commitand adds the command"prepare": "husky"topackage.json(the project's settings file). Thepreparecommand runs on its own whenever someone runsnpm install, so the hooks get installed on your teammates' laptops too.- The first content of
.husky/pre-commitfromnpx husky initisnpm test, which runs thetestscript inpackage.json. In a project made withnpm init -y, thetestscript only printsError: no test specified, then runsexit 1. So every commit fails withhusky - pre-commit script failed (code 1). Replace the content of.husky/pre-commitwith the command you really use. .husky/pre-commitonly needs the command to run, for examplenpx lint-staged. lint-staged runs the linter (the lint program) only on the staged files, not the whole project, so pre-commit stays fast.- Installing Husky doesn't install lint-staged. Install it with
npm install --save-dev lint-staged, then configure it inpackage.json, for example"lint-staged": { "*.js": "eslint --fix" }: ESLint checks and fixes every staged.jsfile. - Those changes to
package.jsonand.husky/are committed like any other files, for example with the messagechore: configure hooks.
There are three ways to share hooks:
- Husky (used here): a good fit for JavaScript projects, because the hooks are installed automatically by
npm install. git config core.hooksPath .githooks: Git looks for hooks in a.githooksfolder that is committed, not in.git/hooks/. It works for a project in any language, but Git's settings are not cloned, so each person runs that command once after cloning.- Hooks in Git's config files (Git 2.54 and later):
hook.<name>.commandholds the command, andhook.<name>.eventholds when it runs, for examplepre-commit.<name>is a name you choose. Withgit config --global, one script can be used in all your repos.
Skipping hooks: --no-verify
In an emergency, you can skip the hooks:
$ git commit --no-verify -m "fix: hotfix login" # skips pre-commit and commit-msg
$ git push --no-verify # skips pre-push
-n is the short form of --no-verify for git commit. Use it only when you must: if you need it often, the hook is too slow or too strict, and the hook is what needs fixing.
⚠️ Hook not doing anything? Check these
- Forgetting
chmod +x. Git skips that hook and only prints a warning that starts withhint: The '.git/hooks/pre-commit' hook was ignored because it's not set as executable.The commit is still made, and the check never runs. - The wrong file name. Git will never run
pre-commit.shorprecommit. - Thinking hooks reach the team.
.git/hooks/isn't committed. Use Husky so the hooks live in the repo. - In the exercise, the hook is already installed. The exercise's
.git/hooks/pre-commitholds theconsole.logexample above, alreadychmod +x, and the exercise terminal runs it on everygit commit. Commands likenpxdon't exist in that terminal, so a hook that calls one fails withcommand not found.
TL;DR: A Git hook is a script in .git/hooks/ that Git runs on its own at a certain moment. The file name must be exactly the hook's name, and the file must be executable (allowed to run, chmod +x). Exit code 0 means carry on, anything else cancels the step: a pre-commit that does exit 1 cancels the commit. The order on commit: pre-commit, then commit-msg (the message is in the file $1), then the commit is made. pre-commit, commit-msg and pre-push are client-side (they run on your computer), pre-receive and post-receive are server-side (they run on the server). Hooks in .git/hooks/ aren't committed, so they don't reach the team. To share hooks, use Husky: the hooks live in .husky/pre-commit, and the prepare command installs them. git commit --no-verify (or -n) skips the hooks, for emergencies only.
⚡ Scripts that run on their own
Meaning: A Git hook is a script (a file of commands) in .git/hooks/. Git runs it on its own at a certain moment, for example right before a commit is made. The file name must be exactly the hook's name (for example pre-commit), with no extension like .sh, and the file must be executable (allowed to run as a program).
⚡ Your first hook: pre-commit
Write:
#!/bin/sh
if grep -q "console.log" app.js; then
echo "pre-commit: app.js still has a console.log, remove it first"
exit 1
fi
echo "pre-commit: all clear"
Meaning: The pre-commit hook runs when you type git commit, before the commit is made. This script looks for console.log (a leftover from debugging, looking for the cause of a bug) in app.js, and stops with exit 1 if it finds one. Save it as .git/hooks/pre-commit, then run chmod +x .git/hooks/pre-commit so it is executable. Exit code (the number a script reports when it ends) 0 means carry on, any other number like exit 1 means Git cancels the commit.
⚡ The commit is cancelled
Guess first: app.js still has a console.log, and you commit. What gets added to git log?
Nothing. The commit is cancelled completely, and all that prints is the hook's message.
Meaning: Remove the console.log, git add again, then commit again. This time the hook prints pre-commit: all clear and the commit is made.
In the exercise, this hook is already installed and already chmod +x.
⚡ Sharing hooks with the team
Meaning: What's inside the .git/hooks/ folder isn't committed, so a teammate who clones your repo doesn't get your hooks. Husky, a tool for JavaScript projects, moves hooks into a .husky/ folder that is committed.