DevOps Blog

Beginner's Guide to Using Husky for Git Hooks with a Step-by-Step Example

A Simple Tutorial on Using Husky for Git Hooks

Husky is a popular tool for managing Git hooks in JavaScript/TypeScript projects. Git hooks are scripts that run automatically when certain Git events occur, such as committing code or pushing to a remote repository.

This tutorial will guide you through setting up Husky in a Node.js project and creating a simple example with a pre-commit hook.

We will test this on a brand new next.js project.


Step 1: Set Up a Node.js Project

  1. Initialize a new Node.js project:

    npx create-next-app@latest husky-tutorial cd husky-tutorial
  2. Install Husky:

    npm install --save-dev husky

Step 2: Enable Git Hooks with Husky

  1. Enable Husky:
    npx husky init
    This command creates a .husky directory in your project, where Git hooks managed by Husky will reside. It will also create a pre-commit hook as an example. This won't work for next but we will fix that in the next step.

Step 3: Edit the pre-commit Hook

  1. Create a pre-commit hook: open the .husky/pre-commit file in your editor and change the contents to the following.

    npm run lint

Step 4: Test the pre-commit Hook

  1. Stage the file for commit:

    git add .
  2. Attempt to commit:

    git commit -m "Test Husky pre-commit hook"

    The pre-commit hook will run npm run lint, which in turn runs ESLint. If there are linting errors, the commit will be blocked.


Recap

  • Husky simplifies the management of Git hooks.
  • Git hooks can automate checks like linting and testing before commits or pushes.