Optimize Vercel preview builds using Ignore Build Step in a monorepo

May 31, 2022 10:58 PM

Ok! So, you’ve got a monorepo with more than one app in it, and some shared packages. You want to only trigger Vercel deployments when necessary rather than building all of your apps.

Checking the diff

The official docs give a few examples depending on your use case. Here’s a combined sample that uses their approach.

There’s a big catch to this approach!

The suggested command of git diff HEAD^ HEAD only compares the commit being checked for build with the previous commit. If you open a PR that has multiple commits, the build will be ignored based only on the changes in the latest commit.

So how do you check for changes based on all commits in a PR? It should be easy? Not so fast! Vercel does a shallow clone using git clone --depth=10 (...) , which only fetches the 10 levels of git history on the current branch. You need more information than is available in the cloned repo to figure out whether a PR introduced changes in the folders you want to check.

The best approach that I found was from probablyup on GitHub — use the GitHub API to set a remote for the shallow clone, and then diff your current commit $VERCEL_GIT_COMMIT_REF against origin/main.

Always build production branches

Depending on your setup, you may want to always build production or staging branches. I added something to my script to account for this.

Putting it all together in a bash script

The vercel.sh script below brings everything together, and is run by putting bash vercel.sh in the ignored build step setting field in Vercel.

Feel free to reach out to me on Twitter @jaronheard if you’ve got thoughts, ideas, or questions on this blog post!