EP 10: Git Hooks - The 'Pre-Flight' Check for Your Code
Source: Dev.to
The Nightmare: “I forgot to run the linter”
We’ve all been there: you’ve been coding for three hours, you’re in the flow, and you finally hit git push. Five minutes later, you get a notification: CI/CD Pipeline Failed.
The culprit? A missing semicolon, a dangling console.log, or a single failing unit test.
It wastes expensive CI/CD compute minutes, clutters your git history with “fix lint” commits, and forces teammates to wait on a “broken” build. In a professional system, human memory is a single point of failure. We need to automate the “bouncer” role.
The Solution: Git Hooks (the Bouncer for your Repo)
Git hooks are scripts that run automatically whenever a specific action occurs in your Git lifecycle (e.g., commit, push, or merge).
Instead of relying on a developer to remember to run npm run lint, we bake it into the system so that code cannot be committed unless it passes your quality standards.
The Power Couple: Husky + Lint‑Staged
- Husky – syncs your Git hooks across the entire team. When a new developer runs
npm install, Husky automatically sets up the hooks on their local machine. - Lint‑Staged – runs checks only on the files you are currently staging (
git add), keeping the workflow lightning‑fast even on large projects.
Implementation Example
{
"husky": {
"hooks": {
"pre-commit": "lint-staged",
"pre-push": "npm test"
}
},
"lint-staged": {
"*.{js,ts,tsx}": [
"eslint --fix",
"prettier --write"
]
}
}
Why this is “System” Design
1. Enforced Standards (Zero Trust)
In a robust system you don’t trust “good intentions.” Regardless of seniority, every team member is forced to follow the same styling, linting, and testing rules, creating a uniform codebase that’s easier to maintain.
2. CI/CD Pipeline Efficiency
Cloud compute for CI/CD pipelines (GitHub Actions, CircleCI, etc.) costs money and time. By catching obvious errors locally, remote runners only deal with code that’s already verified, resulting in a faster feedback loop for the whole team.
3. Preventing “Obvious” Regressions
A pre-push hook that runs your unit tests acts as a safety net, preventing accidental pushes of breaking changes to the main branch and keeping the shared source of truth stable.
Pro‑Tip: The “Atomic” Commit
Using Git hooks to enforce linting and formatting makes every commit in your history “clean.” This simplifies git bisect and git revert because you aren’t sifting through “formatting‑fix” noise.
Takeaway: A system is only as reliable as its automated safeguards. Git hooks turn your repository from a “free‑for‑all” into a high‑integrity environment.