Adding GIT hooks to your project with Husky

Adding Git hooks with Husky

Imagine working in a team of more than 3 developers. Although most of you should not need to imagine. It’s a ground reality for most developers in the corporate world. I assume you are also well aware of the problems we face as the team grows. And if not dealt with appropriately, suddenly it becomes difficult to maintain the coding standards.

We have a bi-monthly developers’ meet at my workplace. We discuss and brainstorm any technical problems any of us might be facing in these meetings. During our last meet up a concern was raised about the code quality. To give you a little background, we use NPM with most of our applications and `npm run lint` and `npm run test` are 2 mandatory NPM scripts that need to be present in our package.json file. And these 2 scripts are configured to run before every Build. So, we have the code quality setup. But this setup does not restrict developers for pushing buggy code to the repositories. And hence we’re facing problems like developers pushing code having linting errors or developers not running unit tests before pushing the code.

So, we decided we wanted to restrict developers from committing/pushing the code without checking basic things like linting errors and unit test failures. Of course, we could write some shell scripts as mentioned here to write the Git hooks, but we were looking for something less time consuming and that’s when we came across Husky.

Husky does exactly what we’re looking for, with no extra code to be written, with a single line command. Just install Husky from NPM, add the hooks in your package.json and you’re done! It’s that simple! Husky abstracts the logic of actual git hooks behind NPM scripts which can be configured in the package.json file like any other NPM script.

Install Husky

npm install --save-dev husky

Add Git hooks to your package.json

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

Once you’ve done this, every time you try to commit something, husky will run `npm run lint` and every time you try to push changes to the remote repository, it will run `npm run test`. If these your lint or test scripts throw any error(s), your commit/push will fail. Of course, you can specify any commands to run of these hooks instead of `npm run lint` and `npm run test`.

Give it a try and let me know your experience in the comments below.

PS: This is NOT a sponsored article. I am just excited to see how effortlessly this package has managed to solve this problem.

Subscribe to our Newsletter to get more such cool articles straight into your Mailbox,

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.