How to create pre-push hook in Git

Pre-push hooks run comprehensive validations before pushing commits to remote repositories, preventing broken code from affecting other developers. As the creator of CoreUI, a widely used open-source UI library, I’ve implemented pre-push hooks in collaborative workflows throughout my 25 years of development experience. The most effective approach is creating an executable script in .git/hooks that runs full test suites and builds. This method catches issues before they reach the remote repository while keeping pre-commit hooks fast.

Create an executable pre-push script in .git/hooks to run comprehensive checks.

#!/bin/sh

echo "Running pre-push checks..."

npm run build
if [ $? -ne 0 ]; then
  echo "Build failed. Fix build errors before pushing."
  exit 1
fi

npm run test:all
if [ $? -ne 0 ]; then
  echo "Full test suite failed. Fix all tests before pushing."
  exit 1
fi

echo "All pre-push checks passed!"
exit 0

Here the script runs a production build first to ensure the code compiles successfully. If the build fails, the script exits with code 1, preventing the push. Next, the full test suite runs, including integration and E2E tests. Only when both build and tests pass does the script exit with code 0, allowing the push to proceed.

Best Practice Note:

This is the pre-push validation we use in CoreUI to prevent broken builds from reaching shared branches. Balance thoroughness with speed—pre-push can be slower than pre-commit since it runs less frequently, use –no-verify flag to bypass hooks in emergencies, and ensure CI runs the same checks to catch any bypassed validations.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author