Husky - An Easy Way To Add Git Pre-Commit Hooks Into Your Project

In today's tutorial, you will learn a simple way to add in git pre-commit hooks to your Javascript project, using Husky.  Husky is a package that when configured correctly, will enforce that your code runs against a pre-commit check that you can define in your packages.json script.  

Git Hooks Explained

Unless you are a complete GIT nerd, then I'm assuming an introduction on git hooks will help.  When you create a new GIT repo, in your repo you should see a folder called '.git' (if not it will be hidden and you're stuck - Google it!).  If you look in here you will see a folder called 'hooks'.  Inside it will contain lots of example scripts - GIT installs them on init - that show you how to do all sorts of really cool things with GIT.  If none of the files have been modified and you look in this folder, you will notice they all have 'sample' in them, meaning they're disabled by default.

Creating your own scripts is doable, but it's a bit of a pain.  You need to write it using PERL, bash etc... and as you only write them once in a blue moon, you'll likely spend time just trying to figure out the information you need.  Most front-end developers are familiar with creating scripts within the packages.json to do things like start the dev server, run unit tests, etc...

When it comes to Git hooks, a much easier approach is to point your GIT hooks to use a script within your packages.json, rather than write something custom in a hidden folder.  This is where Husky comes in.


Husky allows you to create hooks within your packages.json - like 'precommit' and 'postcommit' - that will get triggered when you do a GIT commit. This approach is much nicer and simpler than writing your own GIT hooks, so I recommend you checking it out.

You can install Husky using:

npm install husky --save-dev

In your packages.json, you can then add:

  "husky": {
    "hooks": {
      "pre-commit": "npm test",
      "pre-push": "npm test",
      "...": "..."

After installing Husky, if you look within you .git -> Hooks folder, you can see that Husky automagically creates it's own git hook scripts.  All you need to do is decide what your commit workflow looks like and then testing that it works how you expect it to and that's it.  If you combine Husky with packages like eslint etc.. you can have something pretty powerful, pretty quickly and with the added bonus of not having to write your own scripts.  

submit to reddit

Jon D Jones

Software Architect, Programmer and Technologist Jon Jones is founder and CEO of London-based tech firm Digital Prompt. He has been working in the field for nearly a decade, specializing in new technologies and technical solution research in the web business. A passionate blogger by heart , speaker & consultant from England.. always on the hunt for the next challenge

Back to top