Setting up pre-commit hook:
I am assuming you:
- have already created Next.js app.
- know git
- using pnpm and Windows.
- know what is husky lint-staged eslint prettier
Husky is a popular Git hook tool that helps developers enforce and automate certain actions and scripts before committing or pushing code to a Git repository, like linting code, running tests, formatting code, or performing other custom action.
lint-staged makes quality checks run faster by only checking files you're about to commit.
pnpm add --save-dev husky prettier lint-staged eslint
pnpm exec husky init
# or with npm: npx husky init
- Ensure
package.json
has theprepare
script so Husky is installed afterpnpm install
:
{
"scripts": {
"prepare": "husky"
}
}
Now init husky:
pnpm exec husky init
and edit .husky/pre-commit
and add pnpm exec lint-staged
.
Edit package.json
and add:
"lint-staged": {
"*.{js,jsx,ts,tsx}": [
"eslint --max-warnings=0 --fix",
"prettier --write"
],
"*.{json,md,css,scss,html,yml,yaml}": [
"prettier --write"
]
}
This configuration tells lint-staged to run ESLint with automatic fixing followed by Prettier formatting on JavaScript files, and only Prettier on JSON, CSS, and Markdown files.
Testing pre-commit hook:
Edit any file and add following:
const a = 0;
This is an error variable
a
is not used.
Now run
git add .
git commit -m "Test commit" # this will fail.
Example expected output:
✔ Backed up original state in git stash (93148b8)
✔ Hiding unstaged changes to partially staged files...
⚠ Running tasks for staged files...
❯ package.json — 5 files
❯ *.{js,jsx,ts,tsx} — 1 file
✖ eslint --max-warnings=0 --fix [FAILED]
◼ prettier --write
✔ *.{json,md,css,scss,html,yml,yaml} — 3 files
↓ Skipped because of errors from tasks.
↓ Skipped because of errors from tasks.
✔ Reverting to original state because of errors...
✔ Cleaning up temporary files...
✖ eslint --max-warnings=0 --fix:
[...]\app\page.tsx
3:3 warning 'a' is assigned a value but never used @typescript-eslint/no-unused-vars
✖ 1 problem (0 errors, 1 warning)
ESLint found too many warnings (maximum: 0).
husky - pre-commit script failed (code 1)
Debugging lint-staged issues
When lint-staged doesn't behave as expected, you can debug it by running it with verbose output:
pnpm dlx lint-staged --verbose
You can also test your configuration without making a commit:
pnpm dlx lint-staged --debug
Notes
- CI/CD should also run
pnpm run lint
andpnpm run format
(orformat:write
) to enforce consistency. - Keep local Node/pnpm versions in sync across the team to avoid formatter diffs.
Written on 9/3/25
Top comments (0)