As frontend developers, especially working in teams or production-level apps, keeping our code clean, consistent, and error-free is super important.
Thatβs where Husky comes in β think of it as a helpful friend who makes sure your code is in good shape before you commit or push it.
π€ What is Husky?
Husky is a tool that lets you run scripts automatically at certain Git events, like:
- Before committing code (
pre-commit
) - Before pushing to a remote repo (
pre-push
)
You can use it to:
- Run a linter
- Format code with Prettier
- Run tests
- Run build checks
- ... and more!
π Why use Husky?
Letβs say you're working on a Next.js app. You want to make sure:
- All code follows the same formatting (Prettier)
- There are no linting errors (ESLint)
- Tests pass before code goes to GitHub
- You donβt accidentally push broken code
With Husky, this all happens automatically when you try to commit or push your code.
π Setting Up Husky in a Next.js Project
Letβs walk through how to set up Husky with linting and formatting checks before each commit.
1. Initialize your project (if not already)
npx create-next-app@latest my-app
cd my-app
2. Install required packages
npm install --save-dev husky lint-staged prettier eslint
3. Enable Husky
npx husky install
To make sure Husky sets up every time someone installs your project:
npm pkg set scripts.prepare="husky install"
4. Add a Pre-commit Hook
npx husky add .husky/pre-commit "npx lint-staged"
This means: Every time you commit, Husky will run lint-staged
.
π§Ή Add Lint-Staged Config
In your package.json
, add:
"lint-staged": {
"*.{js,jsx,ts,tsx}": [
"eslint --fix",
"prettier --write"
]
}
This will:
- Run
eslint --fix
on changed JS/TS files - Format them using
prettier --write
β Optional: Add Pre-Push Hook to Run Tests
Want to make sure tests pass before pushing code?
npx husky add .husky/pre-push "npm run test"
Now, every time you push code, tests will run first.
π§ͺ Example Git Workflow With Husky
git add .
git commit -m "Add new feature"
# Husky runs:
# β eslint --fix
# β prettier --write
# β If no errors β commit success
# β If errors β commit fails
π‘ Why This Helps
- No more dirty code sneaking into the repo
- Developers donβt waste time fixing each otherβs formatting
- Consistent style across the whole team
- Tests catch bugs before code reaches production
π Final Thoughts
Even if youβre working solo, Husky can be a big help. It keeps your codebase clean and reduces bugs.
The best way to learn Husky? Use it! Add it to your Next.js project, start small (linting, formatting), and build up (tests, builds, etc).
Happy coding! π»π
Top comments (0)