Per-environment and per-branch Build Commands on Vercel

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.

1. Set up your scripts in package.json

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.

2. Create a vercel.sh file

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.

3. Set your Build Command to use the new file

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

Using a vercel.json file

vercel.json
{
"buildCommand": "sh vercel.sh"
}

Using the project dashboard

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?