Leveraging environment variables in NextJS - passing values to the client side

I'm facing a frustrating issue with my project in server mode. We need to pass environment variables at runtime and access them on both the server and client side.

Following the publicRuntimeConfig method from the documentation, everything works fine when running in dev mode (yarn dev). However, after building the project and deploying it in Docker or Kubernetes, the functionality breaks.

Here is a snippet of the code:

const nextConfig = {
  publicRuntimeConfig: {
    PARAM_A: process.env.PARAM_A || "defaultA",
    PARAM_B: process.env.PARAM_B || "defaultB"
  }
};

module.exports = nextConfig;

In addition, _app.tsx, index.tsx, otherpage.tsx, and help.tsx files contain similar logic for accessing these variables.

The issue arises when moving from the first page to subsequent pages, as the environment variables are not being passed correctly. I want these values to be accessible throughout the entire application. Any guidance on what might be going wrong would be greatly appreciated.

Answer №1

When building your app, the publicRuntimeConfig will be included in the bundle.

The app build process occurs when creating your Docker image. However, at this stage, your environment variables are not accessible.

Upon starting your container, you provide the necessary environment variables for your server-side code to utilize, while your client-side code remains unaware of them.


One potential solution is to initiate the app build during container start, ensuring that it can access the supplied env variables. Yet, I would advise against adopting this strategy.

Alternatively, you can utilize Docker build args to define your environment variables during the build phase:

Dockerfile

ARG PARAM_A
ARG PARAM_B

ENV PARAM_A=$PARAM_A
ENV PARAM_B=$PARAM_B

# ...

Subsequently, pass the environment variables as build arguments:

docker build --build-arg PARAM_A=something --build-arg PARAM_B=something ...

This method enables customization of build arguments for each environment but results in separate images for each one.

I trust this information proves beneficial.

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

Omit functions from category

This question reminds me of another question I came across, but it's not quite the same and I'm still struggling to figure it out. Basically, I need to duplicate a data structure but remove all the methods from it. interface XYZ { x: number; ...

Angular is unable to fetch the chosen option from a dropdown selection

Recently, I encountered an issue with a module form that appears as a pop-up. Within this form, users can input data required to create a new object of a specific class. One field allows users to select a ventilation zone for the new room object being crea ...

Chrome encountered an abnormal exit and failed to start within a Docker container on macOS

When constructing an image on my Mac using FROM selenium/standalone-chrome-debug:3.4.0-chromium in Dockerfile, I encountered the following issue when running my app in the container: org.openqa.selenium.WebDriverException: unknown error: Chrome failed to s ...

Angular 2: Issue with data table not updating after item deletion

I need assistance with updating a data table after deleting an item. The database is updated correctly when I delete an item, but the table does not automatically refresh to reflect the changes. managenews.component.ts import { Component, OnInit } from ...

The TypeScript datatype 'string | null' cannot be assigned to the datatype 'string'

Within this excerpt, I've encountered the following error: Type 'string | null' cannot be assigned to type 'string'. Type 'null' cannot be assigned to type 'string'. TS2322 async function FetchSpecificCoinBy ...

The communication between React and Django APIs on the Kubernetes cluster seems to be experiencing some issues

My journey with Kubernetes is just beginning as I embark on deploying a react-django web app to a Kubernetes cluster for the first time. To accomplish this, I have put together the following: A frontend.yaml file to manage the npm server A backend.yaml f ...

Error in Next.js: .env variable not defined

I recently transitioned my project from React to Next.js and encountered an issue where my environment variables are showing as undefined, even though they were functioning correctly in React. Can someone provide some guidance or assistance with this probl ...

Ensuring TypeScript's strict null check on a field within an object that is part of an

When using TypeScript and checking for null on a nullable field inside an object array (where strictNullCheck is set to true), the compiler may still raise an error saying that 'Object is possibly undefined'. Here's an example: interface IA ...

Achieving a green color for form inputs upon successful validation in a NextJS application using zod

I have integrated the Form component from shadcn and I am curious about customizing the styling of the input based on validation results. Currently, when validation fails, red text displays below the input, but when it passes, the text disappears and the ...

Verifying the format of an object received from an HTTP service using a TypeScript interface

Ensuring that the structure of the http JSON response aligns with a typescript interface/type is crucial for our javascript integration tests against the backend. Take, for example, our CurrentUser interface: export interface CurrentUser { id: number; ...

What are some solutions to the error message "Error: Cannot find any matching routes" that appears when trying to switch between tabs following a successful login?

I am facing an issue with my Ionic 4 (4.10.2 with Angular 7.3.1) app where I want to make it accessible only after login. Following a tutorial from , I encountered a problem when trying to access the ion-tabs section of my app. Chrome keeps showing this er ...

Postpone an automatic action in React

I'm currently working on adding a fade out animation to a page change in React, but I need to delay the click event before the page actually transitions. Here's the code snippet I have so far: export default function Modal({setTopOf}) { const ...

Next.js Development Server Encounters Issue Loading SWC Binary

I've run into a problem with my Next.js project while using the yarn run dev command. The error message can be seen in the image below. Error Details: Next.js Version: 14.0.3 Local Server: http://localhost:3000 Issue Description: The error is relat ...

Is that possible to prevent the use of the & symbol in Angular 4 HTTP requests?

Using an HTTP request to save data in my database. The code snippet I used is: const form = '&inputdata=' + myinput + '&rf_date=' + rf_date; return this.http.post(this.rootUrl, form, {headers : this.reqHeader}); In thi ...

Troubleshooting React TypeScript: Resolving the Error "Argument of type ''""' is not assignable to parameter of type 'SetStateAction<undefined>'"

Currently, I am troubleshooting a React application that was extracted from a live server and now I am attempting to run it on my local machine. However, upon starting up the application locally, I encountered the following error message: Argument of ty ...

The ngAfterViewChecked function seems to be caught in an endless loop

I am facing an issue where the <cdk-virtual-scroll-viewport> starts from the bottom, but I am unable to scroll up. I suspect that this problem is related to the use of AfterViewChecked. Even after trying AfterViewInit, the issue persists. @ViewChil ...

There was an error in the CSS syntax in the production environment due to a missed semicolon

Trying to execute the npm build command "webpack --mode=production --config ./config/webpack.config.prod.js" on our project results in an issue. The issue arises when I include the bootstrap file in my tsx file as shown below. import bs from "../../../../ ...

Learn the proper way to write onClick in tsx with Vue 2.7.13

current version of vue is 2.7.13 Although it supports jsx, I encounter a type error when using onClick event handling. The type '(event: MouseEvent) => Promise<void>' cannot be assigned to type 'MouseEvent' Is there a correct ...

Encountering a 404 error when trying to log in with Next-auth in the development environment

Encountering a 404 error after attempting to log in with Next-auth in a development environment. I am using version next-13.4.9 and next-auth-4.22.1, I have tried several solutions without success. Uncertain of the underlying issue. ...

ReactJS: A single digit input may result in the display of numerous '0's

My goal is to have a small box that only allows one digit, but it seems to work fine until I try to input multiple '0's. Then the box displays multiple 0000 persistently. Here is the code snippet: const InputBox = () => { const [value, ...