How do I add environment variables to my Vercel project?

Vercel Environment Variables are key-value pairs configured outside your source code that change depending on the environment (Local, Preview, or Production).

These values can be used during builds or inside Serverless Functions to read API keys, connect to your database, and more.

Environment Variables UI

You can add Environment Variables to your site through Project Settings. Values are encrypted at rest and permission to view values can be restricted based on your role. You can also choose a specific Git branch to set Environment Variables for with the Preview environment.

The Environment Variables UI in Project Settings.

The Environment Variables UI in Project Settings.

The Environment Variables UI in Project Settings.

The Environment Variables UI in Project Settings.

Accessing Environment Variables

Inside your application, you can access environment variables through process.env.YOUR_VALUE:

import fetch from 'node-fetch';

export default async function handler(request, response) {
  const res = await fetch('https://...', {
    method: 'POST',
    body: JSON.stringify({
      client_id: process.env.CLIENT_ID,
      client_secret: process.env.CLIENT_SECRET,
    }),
    headers: { 'Content-Type': 'application/json' },
  });

  const data = await res.json();
  return response.status(200).json({ data });
}

Using Environment Variables inside of a Serverless Function.

Some frontend frameworks like Next.js require environment variable access on client side to be explicitly defined through the NEXT_PUBLIC_ prefix.

Troubleshooting Undefined Environment Variables

  • Ensure that after adding a new Environment Variable, you have redeployed your application. Environment Variables are made available to the app on each deployment. If you attempt to read an Environment Variable that was added after the deployment was made, it's value will be undefined.
  • If you've added the Environment Variable, but it remains undefined on a new deployment, consider the environment(s) you have added the variable to and make sure the Environment Variable is present in the UI for the type of deployment you are accessing.
  • If you have used vercel env pull to create a local .env file, you can either delete it or use the vercel env pull command to pull the values from your Project Settings into your local file.
  • Printing out the variable's contents is recommended as a troubleshooting step in cases where a function that depends on the variable's value is failing. You can log values directly from your Serverless Function or prefix your build script with echo $MY_ENV_VAR; build command --here.
Updated June 22nd 2022