Set Environment Variables with Next.js and Vercel

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

Photo by Johannes Plenio on Unsplash
  • 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"

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())
};

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”.

That’s all!

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

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

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store