Pre-push build
We'll also use Husky to apply an additional quality check before pushing new commits back to the git server: ensuring that we can actually build the project successfully. We do this pre-push rather than pre-commit since building is a slower step.
Setup
Setup instructions (courtesy of a ChatGPT conversation (opens in a new tab)):
-
Create a new
pre-push
file in the project's.husky
directory -
Paste in the following content:
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
STASH_NAME="pre-push-$(date +%s)"
STASHED_CHANGES=false
# Function to pop stash if changes were stashed
clean_up() {
if [ "$STASHED_CHANGES" = true ]; then
git stash pop -q
fi
exit $1
}
# Set trap to run clean_up function on exit
trap 'clean_up $?' EXIT
# Stash uncommitted changes including untracked, with a unique stash name
git stash push -q --include-untracked --message "$STASH_NAME"
# Check if a new stash was created
if git stash list | grep -q "$STASH_NAME"; then
STASHED_CHANGES=true
fi
echo "Running build before push..."
# Run build
npm run build
- Run
chmod +x .husky/pre-push
to make the file executable
Validation
To validate that the pre-push hook works properly, we'll make a change that will break the Next.js build step:
-
Create a file
src/app/api/test/route.ts
-
Add the content
export function myFunction() {}
Note that when you run npm run lint
, no issues are returned. However, when you run
npm run build
, you get an error:
- info Creating an optimized production build
- info Compiled successfully
- info Linting and checking validity of types ...Failed to compile.
src/app/api/test/route.ts
Type error: Route "src/app/api/test/route.ts" does not match the required types of a Next.js Route.
"myFunction" is not a valid Route export field.
To validate that the pre-push hook is working, commit the changed file (git commit -a -m "Break build"
),
then push (git push
). You'll see that the hook runs the build command and prevents the push from going
forward.