How do I add environment variables to my Vercel project?

The Vercel platform provides the option to define Environment Variables, allowing you to set encrypted strings for sensitive information, such as API keys and database credentials.

Envrionment Variables UI

The best location to store your variables is through the Environment Variables UI in your Project Settings. This is a central location to store Environment Variables that removes the need for any configuration. If you define an Environment Variable, it is automatically encrypted and available to any user that has access to that Project.

You can set variables for Development, Preview, and Production environments separately. In the Preview environment, you can also choose a specific Git branch to set these Environment Variables to.

The Environment Variables UI in Project Settings.

Accessing Variables on the Client

Sometimes you might want to expose Environment Variables on your website directly.

If you are using Next.js, this is all taken care of for you. To access Environment Variables on the client in Next.js, prefix your variable names with NEXT_PUBLIC_ in the Environment Variables UI and when accessing them on the client also.

You can learn more from the official documentation on the conventions required for accessing the variables successfully.

If you are not using Next.js, this can be done by inlining your build time variables through a custom build plugin such as babel-plugin-transform-inline-environment-variables.

Warning:

When making Environment Variables accessible to the client, anyone who inspects your code bundle can determine the values, so make sure not to expose any sensitive information.

Troubleshooting Undefined Environment Variables

  • Ensure that after adding a new Environment Variable you redeploy your app. 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 will be undefined in your app.
  • 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 April 26th 2021