Per-environment and per-branch Build Commands on Vercel

Customize your commands for specific behaviors based on branch, environment, and more.
Last updated on February 2, 2024
Build, Deployment & Git

For certain workflows, it may be useful to execute different scripts based on specific environments or branch names. To do this, you'll create a vercel.sh file in your repository that your Build Command uses to run conditional logic.

First, you'll need the scripts that you want to run. For example, here is are a couple scripts that are meant to run in different environments:

package.json
{
"scripts": {
"build:production": "next build",
"build:preview": "echo \"Let's build a preview!\" && next build"
}
}
Scripts in `package.json` with important differences.

Make a vercel.sh file in your project's root directory. We'll write some conditional logic here to run different scripts in different environments:

vercel.sh
#!/bin/bash
if [[ $VERCEL_ENV == "production" ]] ; then
npm run build:production
else
npm run build:preview
fi

This file is written using Bash but you can also use Node.js. Additionally, this file can be adjusted for other System Environment Variables on Vercel like branch names.

Last, set the project to use the the new file as its entrypoint for the Build Command. You can do this two ways:

vercel.json
{
"buildCommand": "sh vercel.sh"
}
A project using `sh vercel.sh` for its Build Command
A project using `sh vercel.sh` for its Build Command
A project using `sh vercel.sh` for its Build Command
A project using `sh vercel.sh` for its Build Command

Couldn't find the guide you need?