What is the correct way to configure environment variables in a Next.js application deployed on Vercel?

As I develop my web app in Next.js, I have been conducting tests to ensure its functionality. Currently, my process involves pushing the code to GitHub and deploying the project on Vercel.

Incorporating Google APIs dependencies required me to obtain a Client ID and Client Secret for sending emails using node-mailer from the client side through a contact form. While everything functions correctly on localhost, issues arise when deploying to Vercel due to environment variables.

In attempting Solutions A and B

Solution A

I created a .env.local file and defined my variables there, then accessed them in next.config.js where I confirmed their accessibility throughout the application (as indicated by console logs).

.env.local

env:{
    CLIENT_URL:'vxcxsfddfdgd',
    MAILING_SERVICE_CLIENT_ID:'1245785165455ghdgfhasbddahhhhhhhhm',
    MAILING_SERVICE_CLIENT_SECRET:'Rdfvcnsf4263543624362536',
    MAILING_SERVICE_REFRESH_TOKEN:'000000',
    USER_EMAIL_ADDRESS:'<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="740d11070d11070d11070d11070d11070d1107341319151d185a171b19">[email protected]</a>',        
}

next.config.js

module.exports = {
  env:{
    CLIENT_URL: process.env.CLIENT_URL,
    MAILING_SERVICE_CLIENT_ID: process.env.MAILING_SERVICE_CLIENT_ID,
    MAILING_SERVICE_CLIENT_SECRET: process.env.MAILING_SERVICE_CLIENT_SECRET,
    MAILING_SERVICE_REFRESH_TOKEN: process.env.MAILING_SERVICE_REFRESH_TOKEN,
    USER_EMAIL_ADDRESS: process.env.USER_EMAIL_ADDRESS,  
  }
}

Despite implementing Solution A as outlined above, email sending fails to function both on localhost and Vercel.

Solution B

I inserted my variables directly into next.config.js, added it to .gitignore, and pushed to GitHub.

module.exports = {
  env:{
    CLIENT_URL:'http://localhost:3000',
    MAILING_SERVICE_CLIENT_ID:'7777777777777777777777',
    MAILING_SERVICE_CLIENT_SECRET:'R123456789',
    MAILING_SERVICE_REFRESH_TOKEN:'1123456789',
    USER_EMAIL_ADDRESS:'<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="98ebfdf1ebfdf1faf9faf9d8fff5f9f1f4b6fbf7f5">[email protected]</a>',
    
  }
}

Solution B operates effectively on localhost. However, if I introduce an environment variable on Vercel as depicted here, the email transmission ceases to work.

What steps should I take to ensure proper functionality in this scenario?

Answer №1

To easily configure your environment variables in Next.js, you can simply create a .env.local file with your variables without the need to modify your next.config.js file.

# .env.local

CLIENT_URL=vxcxsfddfdgd
MAILING_SERVICE_CLIENT_ID=1245785165455ghdgfhasbddahhhhhhhhm
MAILING_SERVICE_CLIENT_SECRET=Rdfvcnsf4263543624362536
MAILING_SERVICE_REFRESH_TOKEN=000000
<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a4f1f7e1f6fbe1e9e5ede8fbe5e0e0f6e1f7f799ddc1d7ddc1d7ddc1d7ddc1d7ddc1d7ddc1d7ddc1d7e4c3c9c5cdc88ac7cbc9">[email protected]</a>

If you need to make a variable accessible in the browser, prepend it with NEXT_PUBLIC_ as shown below:

NEXT_PUBLIC_CLIENT_URL=vxcxsfddfdgd

You can access this variable in the browser using process.env.NEXT_PUBLIC_CLIENT_URL.

For more information on working with environment variables in Next.js, check out https://nextjs.org/docs/basic-features/environment-variables.


The same concept applies when using Vercel or any other hosting service for your Next.js project. Prefixing your environment variables with NEXT_PUBLIC_ will expose them to the browser.

In Vercel, you can manage environment variables through the Environment Variables section of your Project Settings, matching them with those in your .env.local file.

To learn more about setting up environment variables in Vercel, visit https://vercel.com/docs/concepts/projects/environment-variables.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountering unexpected outputs from JSONify

How can I send the result of a Python function back to my JavaScript using AJAX? Currently, I am receiving this response, but I am expecting either "True" or "False." Here is my jQuery code: var test = $.getJSON("/chk_chn", { name: channel_name }); ...

React-Native-Web generates default classes for inline styles and erroneously applies them in a jumbled sequence

Currently working on a project involving react native web and NextJS. I have encountered an issue with inline styles in React that seems to be caused by RN-Web. It appears that there is a mechanism within the framework that automatically generates classes ...

CSS Bootstrap JS failed to load on localhost upon refreshing the page

Every time I access my localhost Laravel project for the first time, it loads fine. However, when I refresh the page, I start receiving 404 errors for CSS, JS, and other files, causing the layout of the webpage to change. Essentially, Bootstrap JS files ar ...

Exploring the Power of Map with Angular 6 HttpClient

My goal is to enhance my learning by fetching data from a mock JSON API and adding "hey" to all titles before returning an Observable. Currently, I am able to display the data without any issues if I don't use the Map operator. However, when I do use ...

Align the image so that it is perfectly positioned along the lower edge of the window

I have been experimenting with parallax scrolling and resizing images using JavaScript. However, I am struggling to align my homepage perfectly with the edge of the window. The code I have doesn't line up with the bottom edge of the webpage. If I us ...

Leveraging the power of Ajax and Nodejs to dynamically refresh content on a webpage

I'm currently working on creating a loop to refresh a webpage every 30 seconds, but I'm facing some challenges with making an ajax call using the setInterval function. Below is a snippet of my server-side code: var app = express() app.get(' ...

In the world of Express, the res.write function showcases the magic of HTML elements contained within

Currently diving into web app development, I have ventured into using express and implemented the following code snippet: app.post("/", function(req, res) { var crypto = req.body.crypto; var fiat = req.body.fiat; var amount = req.body.amount; va ...

What is the best way to ensure that consecutive if blocks are executed in sequence?

I need to run two if blocks consecutively in TypeScript, with the second block depending on a flag set by the first block. The code below illustrates my scenario: export class Component { condition1: boolean; constructor(private confirmationServic ...

Introducing a Node JS web application unaccompanied by hosting services

As I prepare for a coding competition and want to display my computer's IP address, I am wondering if it is safe to type in my home computer's IP once I start serving the webapp before leaving my house. Apologies if this question seems silly. ...

I am interested in using a loop in Angular to highlight my div element

Enhancing my comprehension regarding the mentioned images. If I don't select anything within the div property, the default style (css) should appear like this, at least when one div is selected. However, the issue arises when unable to select. This ...

Step-by-step guide to automatically submitting a form after obtaining geolocation without the need for manual button-clicking

I am looking for a way to automatically call a page to get geolocation data, and then submit the form to my PHP page with the values of getlat and getlon without the need to click a submit button. I have tried implementing the code below, however, despit ...

What is the procedure to switch the state using useState when an event is activated?

I'm trying to learn React by implementing a basic shop. One idea I had was to have multiple product images and when a user clicks on an image, it flips around to display additional information such as comments and ratings for the product. For this pr ...

Enhance data table by displaying a set number of rows that do not completely fill the table's height

I'm currently attempting to implement a v-data-table with fixed header and footer. However, I've encountered an issue where if I set the table height to be larger than the row height, the table takes on the defined height and the footer ends up b ...

Parsing DXF files using only plain JavaScript

Currently, I am immersed in a CNC project and aiming to convert DXF files into objects using JS. Initially, I attempted using SVGs but the results were not as expected - instead of shapes, the drawings exported as lines (e.g., a square appearing as four se ...

The issue of the useRef object returning undefined in React/React-Native is causing confusion during

Every time I attempt to access the ref object, I keep receiving an error stating that it is 'undefined'. My goal is to map through an array of images and use useRef to access each individual one. To start off, I initialized the useRef like this: ...

Order of setTimeout calls in React's execution sequence

I am currently trying to wrap my head around the functionality of this React component (which is designed to delay the rendering of its children): function Delayed({ children, wait = 500 }) { const [show, setShow] = React.useState(false); React.useEff ...

Is there a way to trigger a "click" on a webpage without physically clicking? So that I can preview the response message before actually clicking

Is it possible to generate a "mock" request to a server through a website in order to examine the response before sending the actual request? Let me clarify with an example: if I were to click on a button on a website, it displays a certain message. I am ...

Manipulating the "placeholder" attribute with Knockout.js and JSON data

Is it possible to use the placeholder attribute with data-bind? I am encountering an error message ([object object]). Can someone help me figure out how to properly utilize it? html: input id="comments" class="form-control" data-bind="attr: { placeholde ...

Adjust the size of the image within a designated container to decrease its proportions when there is an excess of text present

I am working on a project where I need to resize an image based on the available space within its container. When there is text in the description, the image should adjust its size accordingly without pushing the text upwards. I am using React for this pro ...

Visual Latency when Quickly Toggling Between Images in Succession

I have a series of 50 images that need to be displayed sequentially inside a div. The time interval between displaying each image is initially set at 750 milliseconds and decreases with each subsequent image. To ensure all images are loaded before the an ...