Vercel allows you to collaborate seamlessly with your team by providing Preview Deployments for every commit made to your project. In addition to this, you can provide environment variables specific to the Preview environment, ensuring different variables are used for Preview and Production deployments.

In some cases, it can be benefical to use a staging environment, often where production data is used to test the latest changes before making those changes available. While Vercel does not provide a specific environment for this currently, this article covers the steps required to replicate this for your project.

Adding a Staging Domain

To create a staging environment, you'll first need to add a custom domain to your project, to be used for staging only.

You can add a domain by clicking the "Settings" tab from a Project and selecting the Domains section where you can assign multiple domains to the relevant branches.

Warning:

When adding a domain, it is assigned to your default branch automatically. Make sure to click the "Edit" button and assign it to the appropriate branch.

Adding a staging domain from the Vercel Dashboard.

Staging Environment Variables

As mentioned above, Vercel supports Preview and Production deployment targets. By default, the staging branch will use environment variables set for the Preview environment.

It is not possible to change this and so the recommend method is to define a second set of environment variables, specifically for your staging environment, and use a System Environment Variable to help your app decide which set to use.

The simplest way to do so is to define your staging environment variables under the Preview environment, but with a prefix of STAGING_ so that they can be easily identified.

Note:

You can use any prefix of your choosing and are not limited to STAGING_, this is only a recommendation.

Add the System Environment Variable relevant to your Git provider from the options below:

  • VERCEL_GITHUB_COMMIT_REF
  • VERCEL_GITLAB_COMMIT_REF
  • VERCEL_BITBUCKET_COMMIT_REF

By adding this System Environment Variable, your app will be provided with the branch name that the deployment was created from. As a result, you will be able to use this variable to decide which environment variable to use, either the one set for Preview Deployments, or the one you added for the stagine environment. An example of this using JavaScript is show below:

  const host =
    VERCEL_GITHUB_COMMIT_REF === 'staging'
      ? process.env.STAGING_DB_HOST
      : process.env.DB_HOST

Using a System Environment Variable to define which environment variable should be used.


Last Edited on September 18th 2020