Stand-alone Next.js application unable to access environmental configuration file

I am inquiring about a query regarding my Next.js project.

In my project configuration, I have set it to be built in standalone mode for deployment. You can find more information on this link.

experimental: {
    outputStandalone: true
}

As expected, utilizing this feature generates a standalone folder with a server.js.

The main complication arises from the utilization of an environment variable in my source code named NEXT_PUBLIC_API_BASE_URL.

During development mode (using next serve), everything functions properly.

However, when launching the generated standalone file (via node server.js), it fails to work.

It appears that the file is being loaded on the "server side." Upon logging its value in

.next/standalone/server/pages/_app.js
, the correct value is displayed in the node console.

Nonetheless, it seems like Next.js utilizes files located under .next/static/chunks/pages/ and another app.js which does not appear to access process.env (on the browser side).

My assumption was that by prefixing my env var with NEXT_PUBLIC, it should function accordingly; however, this does not seem to be the case.

Do you have any insights into how this operates?

Answer №1

For managing runtime environment variables in your Next.js project, consider utilizing the next-runtime-env package.

To integrate this package, simply add the PublicEnvScript component to your layout.tsx file:

import { PublicEnvScript } from 'next-runtime-env';

export default function RootLayout({ children }) {
  return (
    <html lang="en">
      <head>
        <PublicEnvScript />
      </head>
      <body>
        {children}
      </body>
    </html>
  );
}

Once set up, you can access your environment variables within your code like so:

'use client';
import { env } from 'next-runtime-env';

export default function SomePage() {
  const NEXT_PUBLIC_FOO = env('NEXT_PUBLIC_FOO');
  return <main>NEXT_PUBLIC_FOO: {NEXT_PUBLIC_FOO}</main>;
}

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

Undefined boolean when passing to AngularJS directive

I developed a custom directive that allows for the addition of a gradient background color in AngularJS: .directive('colouredTile', function () { return { restrict: 'A', controller: 'ColouredTileController&apos ...

Error: The `queries` property is undefined and cannot be read (react.js)

Here is the code snippet I am currently working with: import { useState } from 'react' import { QueryClientProvider, QueryClient } from 'react-query' import { ReactQueryDevtools } from 'react-query-devtools' import Navba ...

Capturing the dynamic server response with nested JSON structures

I am in the process of creating a dynamic data-binding function named assemble that requires two input parameters: server response (JSON) - nested JSON object. instruction set (JSON) - a configuration object that dictates the binding. The Issue: The cur ...

Incorporating and utilizing a variable from a separate page in React Native

Screen 1 export class Register extends Component { constructor(props) { super(props); this.state = { number1=0 }; render() { const { number1 } = this.state; v ...

What is the process of accessing information from a customer's form in a server section via the POST approach?

//Here is my client component located in Form/page.tsx "use client" import { useState } from 'react'; export default function Form() { const [name, setName] = useState('') const handleSubmit = async () => { try ...

I encountered an error stating "Module Not Found" while attempting to locate slick-carousel/slick/slick.css. This issue arose while implementing reacy-slick within my Next.js project

While working on my app with Next.js, I wanted to incorporate a carousel like Slick to display images. I followed the official documentation carefully, imported the necessary CSS file, but encountered an error stating "Module Not Found, can't resolve ...

Struggling to display a PHP success message using AJAX

So I have this code where I am trying to create a form in PHP and send a message. The message is being submitted successfully, but I am facing an issue when it comes to displaying a success message. The page submits the data but does not show any output. H ...

Unable to view PDF files on mobile devices within Ionic app, only accessible through browser interface

I utilized the angularjs-pdf library to display a PDF document from a remote source within a mobile app created with Ionic Framework. While it successfully displays the PDF in the browser, on mobile devices it only shows a blank screen. In addition, I re ...

transferring information from a nested input field in Vue to its parent component

I need to send the input data from a child component to the parent component's data property by using the $emit method. Directly binding the transmitted property to the child property using v-bind within the <input v-model="userinput" /&g ...

Tips for modifying the class of a span inline element using a javascript function

Looking for assistance in creating a password text box with an eye icon that toggles visibility. When the user clicks on the eye icon, it should change to a crossed-out eye icon and switch the input type to text. <div class="input-group show-hide-passw ...

Store the value returned by the function(data) from the $.post method in a variable

Hello Fellow Developers! I'm currently working on a coding project with the following objective: My goal is to extract URLs of files stored in a specific folder and then store them in an array using JavaScript. Here's how I envision the proces ...

transfer data between web pages using JSON

I'm trying to extract a JSON object with the following function: function getPost() { var fname = document.getElementById("fname").value; var lname = document.getElementById("lname").value; var v = { "name": { ...

Issue with generating random cells in a table using a loop

Within my HTML code, I have a table constructed using the table element. To achieve the goal of randomly selecting specific cells from this table, I implemented a JavaScript function that utilizes a for loop for iteration purposes. Despite setting the loop ...

"Combining Array Elements in jQuery: A Guide to Merging Two Array Objects

enter : var b= [{ "cat_id": "1", "cat_name": "teaching" }]; var a= [ { "username": "r", "password": "r" }]; I desire the following result: [{"username":"r","password":"r","cat_id":"1","cat_name":"teaching"}] ...

Is there a way to format wrapped lines with indentation in an unordered list?

Is there a way to indent the wrapped lines of text in an unordered list? The current layout is not quite what I want, as shown in the first image below. Ideally, I would like it to look more like the second image. I attempted to use margin-left: 56px; and ...

A guide to accessing items imported from a glb file within the Babylon JS game engine

When I use the BABYLON.SceneLoader.ImportMesh() method to load a .glb file created in Blender, one of the objects is named Cube.003. Surprisingly, after calling the method, Cube.003 is not included in the scene.meshes array. It does show up in the scene ...

AngularJS resource failing to generate correct URL structure

I'm encountering an issue with AngularJS resources. The resource I have is structured as follows: loginModule.service('TestResource', function ($resource, $location) { var $scope = this; $scope.resource = $resource(window.location. ...

What is the best way to display each value from the array arr, containing strings, on separate lines?

Can you complete the function below to display each value in the array 'arr' on separate lines? <!DOCTYPE html> <html> <head> <title> ...

What is the best way to update the innerHTML of a date input to reflect the current value entered by the user?

Currently, my task involves extracting data from a table by obtaining the innerHTML of each row. The table contains date inputs that can be manually adjusted or generated automatically. However, the innerHTML does not update accordingly. Thus, when exporti ...

Display and view .dwg files using Javascript, HTML, and Angular

Looking for a way to upload and preview .dwg format images on a page created using js/HTML/angularjs or Angular 2+? I've attempted to use a CAD viewer js library, but the lack of documentation has made it challenging. Has anyone successfully implement ...