A Git hook is a local executable that Git runs at a named event. For a basic repository using the default hooks directory, save this as .git/hooks/pre-commit:
#!/bin/sh
# Check the project before committing.
# Author: Ishan Karunaratne - https://techearl.com/git-hooks-explained
npm run lintThen enable it:
chmod +x .git/hooks/pre-commitThis assumes the project already has a working lint script and installed dependencies. A nonzero result blocks the commit. It checks the working tree according to that script, not an isolated copy of exactly what is staged. For staged-file handling, use the lint-staged example below.
This page covers the local hooks (pre-commit, commit-msg, pre-push), sharing them with core.hooksPath or Husky, lint-staged, and bypassing and troubleshooting. On the server side, it covers push-to-deploy with a post-receive hook and the GitHub Actions alternative.
What is a Git hook?
Git recognizes specific filenames such as pre-commit, commit-msg and pre-push. A file named pre-commit.sample is only a sample; remove the suffix and make it executable to activate it. The interpreter comes from the shebang, so shell, Python and Node hooks all need their runtime installed where Git runs.
The default location is $GIT_DIR/hooks. In an ordinary checkout that is .git/hooks, but linked worktrees, bare repositories and core.hooksPath can change the layout. Check a configured override with:
git config --show-origin --get core.hooksPathNo output normally means no override is configured. Do not assume .git is always a directory; worktrees can use a .git file pointing to metadata elsewhere.
Common hooks and when they run
| Hook | When it runs | Typical use |
|---|---|---|
pre-commit | Before recording the commit | Fast checks or a linter |
prepare-commit-msg | Before the commit-message editor | Populate a ticket or template |
commit-msg | With the proposed message file | Validate message format |
post-commit | After the commit | Local notifications |
pre-push | Before transferring the push | Tests or an accidental-push check |
post-checkout | After a checkout or branch switch | Refresh local derived files |
post-merge | After a successful merge | Report dependency changes |
Blocking behavior belongs to each hook's documented contract. pre-commit, commit-msg and pre-push can reject their operation with a nonzero exit status. A post-commit notification cannot undo the commit that already happened.
Server-side hooks are a different enforcement point. See pre-receive hook declined for rejected pushes, and deploy with a post-receive hook below for push-to-deploy on your own server.
A pre-commit hook with useful failure output
A little output makes failures easier to diagnose:
#!/bin/sh
# Run the repository lint script before a commit.
# Author: Ishan Karunaratne - https://techearl.com/git-hooks-explained
te_log() {
printf '[pre-commit] %s\n' "$1"
}
te_log 'running npm run lint'
if ! npm run lint; then
te_log 'lint failed; commit aborted'
exit 1
fi
te_log 'lint passed'For example, a configured linter could report:
[pre-commit] running npm run lint
src/login.js: an unused variable failed the lint check
[pre-commit] lint failed; commit abortedThe exact linter output depends on its configuration. Fix the error, stage the intended fix and retry. Git has not created a commit when pre-commit rejects it. An unstaged change can also cause this full-working-tree check to fail, even when the staged change is valid.
Share native hooks with core.hooksPath
Files inside .git/hooks do not travel with a clone. To review and version the scripts, move them into a tracked directory:
mkdir -p .githooks
mv .git/hooks/pre-commit .githooks/pre-commit
chmod +x .githooks/pre-commit
git config --local core.hooksPath .githooks
git add .githooks/pre-commitCommit the tracked file through the normal project workflow. Each new clone still needs the local activation step:
git config --local core.hooksPath .githooksInspect the scripts before enabling them. A tracked hook executes code from the repository, including future updates to that hook; cloning alone deliberately does not activate arbitrary repository scripts. A setup script can make activation convenient without hiding this trust decision.
Choose one owner for core.hooksPath. A native .githooks setup and Husky should not compete to configure the same clone.
Share hooks with Husky
For an npm-based project, the current Husky setup is:
npm install --save-dev husky
npx husky initinit adds a prepare script and creates .husky/pre-commit. Edit that file to contain the command you want:
npm run lintCommit the project configuration, lockfile and .husky/pre-commit. Husky's current generated launchers live in .husky/_, and it points core.hooksPath there; the editable hook remains in .husky/pre-commit. Do not manually point Git at the wrong directory or copy old Husky bootstrap lines into a current installation.
Installation needs its lifecycle script to run with Git available. A clone with scripts disabled, development dependencies omitted or HUSKY=0 is not automatically protected. Treat the local hook as useful feedback and keep required checks in CI.
Lint only the staged changes with lint-staged
A pipeline that extracts filenames from git diff and sends them to xargs is easy to get wrong. It can split paths with spaces, omit renames, or lint unstaged content in a partially staged file. I use lint-staged for that workflow:
npm install --save-dev lint-stagedMerge this key into package.json; the relevant ESLint and Prettier dependencies and configuration must already exist:
{
"lint-staged": {
"*.{js,jsx,ts,tsx}": "eslint --fix",
"*.{css,md}": "prettier --write"
}
}Change .husky/pre-commit to:
npx lint-stagedBy default, lint-staged creates a backup stash and hides unstaged changes in partially staged files while tasks run, then restores them. Successful task changes are included in the commit. Those safeguards are configurable, so do not disable them casually. Test the setup with a filename containing spaces and with a partially staged file; review the resulting diff when a formatter changes code.
Lint-staged runs commands on matching paths. It is not a substitute for a full build or test suite that depends on the whole project.
Bypassing and disabling hooks
git commit --no-verify -m "Describe the change"
git push --no-verifyFor git commit, --no-verify skips pre-commit and commit-msg; it does not skip prepare-commit-msg. For a push, it skips pre-push. A user can also change or remove their local hooks, so they are not a security boundary. Required CI checks and protected-branch policy provide enforcement at the shared repository.
To disable a raw hook temporarily:
chmod -x .git/hooks/pre-commitFor a custom hooks path, use the actual configured file. To remove a custom configuration after uninstalling the tool that owns it:
git config --local --unset core.hooksPathThat returns this clone to its default path unless a higher-level Git configuration supplies another value.
Why a hook does not run
Check the filename, executable permission, shebang and current core.hooksPath. Also check whether the event really occurred: an editor opening is not evidence of a completed commit, and an interrupted merge is not a successful post-merge event.
A GUI Git client can have a different PATH from your interactive shell, especially when Node comes from a version manager. Run the command under the same environment and check the tool's own troubleshooting instructions. On Windows, preserve LF line endings in shell hooks. Non-executable hooks may produce Git advice rather than a hard error.
Deploy with a post-receive hook
Hooks also run on the server side, and the most useful one there is post-receive: Git runs it right after a push lands. Pair it with a bare repository on your own server and git push production main becomes your deploy command, with no CI vendor and no SSH-in-and-pull dance.
Why the server repo is bare
A normal repository has a working directory, and you cannot safely push to a branch that is checked out in it, because the working tree and the branch pointer would disagree. A bare repository has no working directory, just the objects, refs and hooks, which is exactly what a remote should be. The hook then materializes the files somewhere else. So the server has two directories:
- A bare repo that receives pushes, e.g.
/srv/git/myapp.git - The live deploy target, e.g.
/var/www/myapp
On the server (once ssh user@host works; if it throws Permission denied (publickey), see the Permission denied (publickey) fix first):
mkdir -p /srv/git/myapp.git
cd /srv/git/myapp.git
git init --bare
mkdir -p /var/www/myappgit init --bare puts hooks/, objects/ and refs/ directly in myapp.git/ rather than inside a .git subfolder. That is correct.
The post-receive script
cat > /srv/git/myapp.git/hooks/post-receive <<'EOF'
#!/usr/bin/env bash
set -euo pipefail
# Deploy hook for myapp
# Author: Ishan Karunaratne - https://techearl.com/git-hooks-explained
WORK_TREE="/var/www/myapp"
GIT_DIR="/srv/git/myapp.git"
DEPLOY_BRANCH="main"
te_log() {
echo "[deploy] $1"
}
te_deploy() {
local ref="$1"
local branch="${ref##refs/heads/}"
if [ "$branch" != "$DEPLOY_BRANCH" ]; then
te_log "skipping $branch (only $DEPLOY_BRANCH deploys)"
return 0
fi
te_log "deploying $branch to $WORK_TREE"
git --work-tree="$WORK_TREE" --git-dir="$GIT_DIR" checkout -f "$branch"
te_log "done"
}
while read -r oldrev newrev ref; do
te_deploy "$ref"
done
EOF
chmod +x /srv/git/myapp.git/hooks/post-receiveset -euo pipefailstops the hook at the first failing command and prints the error back to the pusher. It cannot reject the push:post-receiveruns after Git has already updated the refs, so the push succeeds either way. To refuse a push, use apre-receivehook; to avoid a half-deployed site, build somewhere separate and switch over only on success (see the build step below).post-receivereceives one line per pushed ref on stdin, formattedoldrev newrev refname, which is why the ref is read in awhile readloop rather than from an argument.- The branch filter means pushing a feature branch does nothing; only
maindeploys. Sincemainis the branch that ships, protect it on the origin so nothing lands there without review. git --work-tree=... --git-dir=... checkout -fforces/var/www/myappto match the pushed branch.-fdiscards hand-edits in the work tree, which is what you want: the repo is the source of truth.
Back on your local machine, add the server as a remote and push:
git remote add production user@your-server.com:/srv/git/myapp.git
git push production mainYour [deploy] log lines stream back over SSH, and /var/www/myapp holds the latest code. checkout -f writes exactly what Git tracks, so a file you never committed, or one in your .gitignore, never reaches the server. Either commit it (never secrets) or provision it on the server separately, and keep the bare repo out of any web-served path.
Add a build step
For a static site or a compiled app, build between the checkout and "done". With set -e on, a failing build stops the hook before "done" (the push itself has already been accepted):
te_deploy() {
local ref="$1"
local branch="${ref##refs/heads/}"
[ "$branch" != "$DEPLOY_BRANCH" ] && return 0
te_log "deploying $branch"
git --work-tree="$WORK_TREE" --git-dir="$GIT_DIR" checkout -f "$branch"
cd "$WORK_TREE"
npm ci
npm run build
npm prune --omit=dev
te_log "done"
}npm ci installs the full dependency set because build tools usually live in devDependencies; npm prune --omit=dev strips them back out after the build. One honest limit: if the build fails, the working tree is already updated but the build is stale. For anything beyond a trivial site, deploy into a fresh directory and swap a symlink only after the build succeeds.
When the deploy hook does not fire
- The hook does not run. The file must be
hooks/post-receiveexactly (no.sh, no.sample) and executable. Check thexbits withls -l hooks/post-receive. - Wrong shell. The shebang must point at a real shell on the server; some minimal images only have
/bin/sh. - Permission denied writing the work tree. The SSH user that receives the push must be able to write
/var/www/myapp. A mismatch between the git user and the web user is the classic failure. - The push succeeds but nothing deploys. The
DEPLOY_BRANCHfilter is probably rejecting the branch you pushed. Add ate_log "got $branch"line to see what the hook receives.
Push-to-deploy with GitHub Actions
The other deploy style moves the work off your server: with GitHub Actions, a YAML file in .github/workflows/ tells GitHub to build, test and deploy on every push to main. A workflow has three nested parts: an event triggers it (a push, a pull request, a schedule, a manual click), a job runs on one fresh runner machine, and steps run top to bottom inside the job. Here is a workflow for a Node.js project on a server you can reach over SSH, saved as .github/workflows/deploy.yml. The runner tests and builds the commit; the server then checks out that exact commit and builds it itself, so what ships is the code that passed:
name: Deploy
on:
push:
branches: [main]
jobs:
build-and-deploy:
runs-on: ubuntu-latest
steps:
- name: Check out the code
uses: actions/checkout@v4
- name: Set up Node
uses: actions/setup-node@v4
with:
node-version: 26
- name: Install dependencies
run: npm ci
- name: Run tests
run: npm test
- name: Build
run: npm run build
- name: Deploy over SSH
uses: appleboy/ssh-action@v1
with:
host: ${{ secrets.DEPLOY_HOST }}
username: ${{ secrets.DEPLOY_USER }}
key: ${{ secrets.DEPLOY_SSH_KEY }}
script: |
set -e
cd /var/www/myapp
git fetch origin main
git checkout --detach ${{ github.sha }}
npm ci
npm run build
npm prune --omit=dev
pm2 restart myappon: push: branches: [main]is the trigger; pushes to other branches do not deploy.actions/checkout@v4clones the repo onto the runner, which is otherwise an empty machine;actions/setup-node@v4installs the Node version you ask for.- If
npm testornpm run buildfails, the job stops and the deploy step never runs. That ordering is the safety net. - The deploy step SSHes into the server, checks out the exact commit the runner tested (
github.sha), builds it there and restarts. The runner's build output stays on the runner; it is a gate, not the artifact that ships. If you would rather ship the runner's build, upload it as an artifact or copy it withrsync/scpin the deploy step instead of rebuilding. Keep the server's checkout clean and let the workflow own it, or the checkout can fail on a file someone edited in place.
For the Node setup half in more depth (caching, matrix builds), see setting up Node in a GitHub Actions workflow. If you want to prove the pipeline before wiring a server, start with just the checkout, setup-node, npm ci and npm test steps, break a test on purpose, and watch the red X appear in the Actions tab.
Keep secrets out of the YAML
The deploy step never contains a password or key; it reads secrets.DEPLOY_SSH_KEY and friends from the repo's encrypted secret store. The workflow file is committed, so anything written in it is visible to anyone who can read the code and stays in history. Add secrets under Settings, Secrets and variables, Actions, New repository secret. The runner can read them at run time, nobody can read them back out of the UI, and GitHub masks them in logs. I use one secret per credential and a deploy-only SSH key (public half in the server's authorized_keys, private half in the secret), never my personal key. If a credential ever lands in a commit, rotate it and scrub it from history.
Push-to-deploy also makes main load-bearing: whatever lands there ships. Route changes through pull requests, let CI run on the PR, and merge only when it is green.
post-receive hook vs GitHub Actions
| post-receive hook | GitHub Actions | |
|---|---|---|
| Where deploy runs | On your server, triggered by your push | On the vendor's runners, triggered by a push to GitHub |
| Dependencies | SSH access to the box, a bare repo | A GitHub repo, a workflow file, and (for this recipe) SSH access from the runner |
| Build step | You run it in the hook (or skip it) | Runs on the runner before deploy |
| Cost / vendor | None beyond your server | Free tier, then metered |
| Secrets handling | Server env / files you manage | Encrypted repo secrets |
| Best for | A single VPS you control, simple sites | Multi-step pipelines, tests-then-deploy, teams |
Neither is better in general. The hook is the leanest thing that works for one server; Actions is the right call when tests should gate the deploy or you want the pipeline to live with the code. Both recipes here need SSH to the server; for a target without SSH (a PaaS, object storage, a container registry), swap the deploy step for that platform's own deploy action.
FAQ
See also
Sources
Authoritative references this article was fact-checked against.
- Git hook events and behaviorgit-scm.com
- Git core.hooksPathgit-scm.com
- Husky setuptypicode.github.io
- Husky hook-path implementationraw.githubusercontent.com
- lint-staged usage and safeguardsgithub.com
- Pro Git: Setting Up the Server (bare repos over SSH)git-scm.com
- git init documentation (--bare)git-scm.com
- Workflow syntax for GitHub Actions | GitHub Docsdocs.github.com
- Using secrets in GitHub Actions | GitHub Docsdocs.github.com
- Understanding GitHub Actions | GitHub Docsdocs.github.com
- Workflow artifacts | GitHub Docsdocs.github.com





