Git hooks setup using Husky

Sailesh Subramanian
3 min readJun 13, 2021

Add Git hooks to your next web development project to ensure policies and handle deployment tasks trouble-free.

Photo by James Harrison on Unsplash

There are exceptionally well code quality tools available in market. Most front end developers rely on eslint as code quality tool in their application. In this article we will discuss about a tool called Husky, which makes our life easier.

Quite often you may have missed to run the linting and pushed the code. You will realize it when the pipeline breaks there is nothing more annoying than that. Husky is a tool that facilitates adding GIT hooks to the project. So before you push /commit your code it helps us run certain script automatically.

Hooks are basically some sort of scripts that can be run when any action happens. When it comes to GIT those actions can be commit, push etc.

Let’s create a sample nodejs code to explain the tool husky with help of eslint.

Run npm init to generate a package.json . Create an index.js file. Add simple node server code to test out eslint. Add express to our project by running npm i express.

const http = require("http");
const express = require("express");
const app = express();
const server = http.createServer(app);
app.get("/", (req, res) =>{
res.send("Welcome to husky tutorial");
}
const port = 5000;
server.listen(port);
server.on("listening",() => {
console.log("Server up and running");
});

Now that our test code is created, if you give command node index.js in vscode console , you could see “Welcome to husky tutorial” in localhost:5000 in browser. But that’s not the main point of this article. Let’s add husky to our project. You will find detailed documentation about husky in here

Type in the command npx husky-init && npm install in the vs code console. It is the automatic way (recommended by husky) of installation and it will setup your project with husky including changes in the package.json . Though the manual way of installation is also possible , if you are new to this, I recommend you to choose the easy way.

If you check your project structure your should see a new folder .husky added. Open the pre-commit file. Edit the default npm test command to npm run lint .

To test our pre-commit hook is working as expected, let’s add eslint npm install eslint --save-dev .Type in the command eslint --init and answer a bunch of questions it will generate the eslintrc.json file for you.

Edit the package.json and add the following in the scripts section

"lint": "eslint index.js","lint:fix": "npm run lint -- --fix",

Setup your repo and the next time you do the commit, your pre-commit hook will run and will save you a lot of time considering the unexpected lint errors in the pipelines without husky.

Happy coding !!

Cheers.

--

--

Sailesh Subramanian

Front End Engineer @ Tata Consultancy Services Ltd. Cricket enthusiast. Small time writer.