Set Environment Variables with Next.js and Vercel

Aude Faucheux
2 min readMay 23, 2020

How to set environment variables for API URLs, passwords, secret keys…

Photo by Johannes Plenio on Unsplash

In this example, the app needs to fetch all the users from an API and display it as a list. But the API URL varies depending on which environment it’s running on:

  • if the app is running locally, it should fetch users from “http://localhost:3004
  • if the app is running in production, it should fetch users from “https://production-api-example”

1. Add “.env.local” file

Create a file in the root directory and name it .env.local
Then set the environment variable for development:

SERVER="http://localhost:3004"

If you want to save confidential variables locally such as password, API keys and secrets, make sure you don’t commit .env.local to your version control manager (eg: Github) by adding .env.local to .gitignore.

2. Add “next.config.js” file

Create a file in the root directory and name it next.config.js. Then paste the below code:

module.exports = {
env: {
SERVER: process.env.SERVER,
},
};

3. Access the environment variable in the API call

Once the next config file is set, you can access the environment variable via process.env and use it in the API call

const server = process.env.SERVER;getUsers = () => {
return fetch(`${server}/users`)
.then(res => res.json())
};

The app should now work locally (you might need to restart your dev server). However, we still need to set the SERVER variable for production.

4. Add the Production variable to Vercel

Open the app’s project on Vercel and click on Settings. Scroll down to the environment variable section, set the production environment variable, and click on “Add”.

Trigger a new Deployment to apply your changes, for example by pushing/merging changes to your master branch.

That’s all!

For further details, please refer to Next.js and Vercel documentation:

Below the repository of the user list app for reference:

Please don’t hesitate to leave feedback and questions in the comments :)

--

--

Aude Faucheux

JavaScript Mid-Level Developer, I write blogs to learn and share what I learn.