What is the process for configuring browser environment variables in Next.js with the `"type": "module"` setting?

While working on my nextjs project, I have encountered an issue with setting environment variables that can be accessed at the browser level.

Whenever I use console.log(process.env), it always returns {} in the javascript console, and any variable like process.env.<variable> shows an undefined value.

I have tried following the instructions for setting up environment variables using next.config.js and .env file with the NEXT_PUBLIC_ prefix. However, none of these methods have worked for me. I believe that most of the information I found does not apply in my case because I am using

"type": "module"
in my package.json file:

{
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "test": "NODE_ENV=test mocha --require @babel/register --require ignore-styles",
    "run": "--require @babel/register --require ignore-styles"
  },
  "dependencies": {
    ....
  },
  "devDependencies": {
    "@babel/core": "^7.21.0",
    "@babel/plugin-transform-modules-commonjs": "^7.21.2",
    "@babel/register": "^7.21.0",
    "babel-preset-react-app": "^10.0.1",
    ...
  },
  "type": "module"
}

Here is my next.config.js file:

/**
 * @type {import('next').NextConfig}
 */
const nextConfig = {
  env: {
    custom_key: 'test1234',
    TEST: 'asd!!'

  },
  pageExtensions: ['mdx', 'md', 'jsx', 'js', 'tsx', 'ts'],
  webpack: config => {
    config.module.rules.push(
      {
        test: /\.html$/i,
        loader: "html-loader",
      }
    );
    config.resolve.extensions = ['.ts', '.tsx', '.js', '.jsx', ...config.resolve.extensions]
    return config;
  }
};

export default nextConfig;

However, when I try to access process.env.custom_key or process.env.TEST, I always receive undefined.

I have also attempted to define these variables (e.g. NEXT_PUBLIC_TEST) in the .env or .env.local files, but in that case, I still get

process.env.NEXT_PUBLIC_TEST = undefined
.

Everywhere I look, the solution suggested involves using:

module.exports = {
  env: {
    customKey: 'my-value',
  },
};

However, due to using

"type": "module"
, I am unable to use this. So, my question is, what am I missing here? Is my nextConfig incorrectly defined? What do I need to change in order to use environment variables at the browser level?

At the server level, process.env seems to be working fine as it prints everything from my .env and env.local files, but does not reflect what I have in the next.config.js file.

Answer №1

Success! By updating nextjs from version 13.1.6 to 13.4.0, the issue has been resolved.

I have now configured environment variables using the NEXT_PUBLIC_ prefix in my .env.local file, and all functionality is operating as intended.

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

To customize or not to customize?

Lately, there has been a growing trend of people incorporating custom attributes into their HTML tags to add extra data for use in JavaScript code. I'm curious to hear thoughts on the practice of using custom attributes and what alternatives are avai ...

Omitting a specific element from the design of the current child route in Next.js 13

How can I modify the root layout in Nextjs 13 using the app router to exclude a specific element from being rendered in a child route? Specifically, I want to remove the aside with the Feed component while keeping the rest of the code intact: // Exclude ...

What is preventing the specific value in React state from being updated?

Starting off as a beginner, but I'm giving it a shot: In my React project, users input landing pages and I aim to extract data from these pages using JQuery and RegEx, then update the state with the extracted value. The issue I'm facing is that ...

jQuery tooltip box not functioning correctly

When the mouse enters on li a, the tooltip box (class .show_tooltip) is appearing on the left. I want each tooltip box to display just above or to the left of the link that the mouse is on. The links need to stay on the right as they are now, so please do ...

Attempting to create a fresh string by substituting certain characters with different ones

Exploring TypeScript, I encountered a puzzle where I needed to substitute specific characters in a string with other characters. Essentially, replacing A with T, T with A, C with G, and G with C. The initial code snippet provided to me looked like this: e ...

"Utilizing Vue.js to make an AJAX request and trigger another method within a

How can I include another method within a jQuery ajax call? methods : { calert(type,msg="",error=""){ console.log("call me"); }, getData(){ $.ajax({ type: "GET", success: function(data){ / ...

Leveraging TypeScript's "this" keyword within an interface

I am currently working on a personalized interface where I aim to determine the type of an interface value within its implementation rather than in the interface definition, without using generics. It is important to note that these implementations will al ...

The process of assigning a function to an object in JavaScript is currently not functioning properly

After updating a Vue2 project to Vue3, I ran into an issue with Javascript. It seems that the language now prevents me from assigning a function to an object. In the code below, I define a function "bar" within a loop. While I can successfully call the fu ...

What is the best way to prevent labels from floating to the top when in focus?

How can I prevent the label from floating on top when focusing on a date picker using Material UI? I have tried several methods but nothing seems to work. I attempted using InputLabelProps={{ shrink: false }} but it did not resolve the issue. Here is a li ...

Node server optimization for images

Currently, I have a server set up for uploading images. In order to enhance the image upload process, I am looking for ways to optimize it. This is my current function for uploading files: uploadImage(file, uid, res) { var fs = require('fs') ...

What is the significance of using composability over the deprecated method in Reactjs Material-UI menuItems?

I have taken over a project that was built using an older version of react, and I am currently in the process of updating it. However, I encountered console errors right off the bat. Error : bundle.js:6263 Warning: The "menuItems" property of the "Left ...

Having trouble receiving a response from axios

My goal is to use axios to submit a blog post and display a response message. If the response is "success," the process should proceed. For testing purposes, I am only using console.log("success ok"). However, I encountered a puzzling issue that I cannot f ...

The React array map function seems to be creating a duplicate of the array within an array of objects

When creating a movie application, the challenge arises when showtimes are embedded in an array of objects inside an array of movie objects. The issue is that the times are duplicating, causing the movie to render multiple times based on the number of show ...

Establishing a pair of separate static directories within Nest

I am looking to utilize Nest in order to host two static applications. Essentially, I have a folder structure like this: /public /admin /main Within my Nest application, I currently have the following setup: app.useStaticAssets(join(__dirn ...

Retrieving PHP variable within a JavaScript file

I have a PHP script running on my server that tracks the number of files in a specific directory. I want to retrieve this file count ($fileCount) in my JavaScript code. numberOfImages.php: <?php $dir = "/my/directory/"; $fi = new FilesystemIterator($d ...

The Ajax script seems to be failing to update the PHP file along with its corresponding variable value

I have a simple form where upon clicking the "=" button, I want the calculated value to be displayed in file process.php. However, this functionality is not working for me. It seems that when the "=" button is clicked, nothing happens. The default value in ...

Converting JSON information into a JavaScript array

var test=[]; $(document).ready(function(){ $.getJSON("data.json",function(data){ $.each(data,function(key,value){ test.push(value.topic); }); }); }); I have written some j ...

Steps for registering a function on $rootScope when angularjs is ready

In order to make a method accessible throughout angularjs, I am looking to register it with 2 arguments (the resource id and the delete callback) using the resource provider to handle the deletion process. To properly register this method, I need angularj ...

Adjust the month to be plotted on the X-axis of the ColumnChart using the specified

My ORIGINAL POST: I've put together a fiddle to showcase how my data is sourced from JSON and displayed in a ColumnChart. https://jsfiddle.net/w4dokdt9/3/ This is an example of how my JSON data is structured: [{"lPlusScoreID":1,"jan":60.03,"feb":4 ...

Tips for generating multiple HTML hyperlinks using a for loop in a Chrome extension

function createDropDown(){ const tree = document.createDocumentFragment(); const link = document.createElement('a'); for(let index = 0; index < urlList.length; index++){ link.appendChild(document.createTextNode(urlList[index])); ...