Git Hooks with Husky

Git Hooks with Husky

posted in dev-setup on

Avoid pushing changes that break the build with githooks and Husky.

typicode/husky : 🐺 Git hooks made easy


git hooks
Run a program before certain points in gits execution.

They are defined in .git\hooks.
You can find some example files in that directory. Remove their .sample suffix to test them out.


Hooks are saved locally and not pushed to the remote. Husky allows you to easily make the git hooks part of the repository itself.

npm install husky --save-dev

Add to package.json

  "husky": {
    "hooks": {
      "pre-push": "bash",
      "pre-commit": "npm run lint"

It’s also possible to put the json (without the husky node) in a .huskyrc or .huskyrc.json file.

Prepush script that works around the frontend project package.json not being in the root of the git repository.


# Path Juggling
if [ "`git rev-parse --show-cdup`" != "" ]; then cd `git rev-parse --show-cdup`; fi
cd ./frontend-project-folder/

# Linting
npm run lint
if [ $? -ne 0 ]; then
    cd $originalPath
    exit -1

# Testing
npm test
if [ $? -ne 0 ]; then
  cd $originalPath
  exit -1

# Build
npm run build

cd $originalPath
exit $hasBuildErrors


More control with .huskyrc.js and environment variables.

const tasks = arr => arr.join(' && ');

module.exports = {
  'hooks': {
    'pre-commit': tasks([
      'echo $HUSKY_GIT_PARAMS',
      'echo $HUSKY_GIT_STDIN',
      'echo $HUSKY_DEBUG',
      'echo $HUSKY_SKIP_INSTALL'

Other interesting reads
Tags: git