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

Is it necessary for the version of the @types packages in TypeScript to match their non-types packages?

Are @types and untyped packages versioned the same way? npm i bluebird @types/bluebird -S returns "@types/bluebird": "^3.5.0", "bluebird": "^3.5.0", This seems logical. npm i request @types/request -S yields "@types/request": "0.0.41", "request": "^2. ...

Can we merge tailwind.config.js settings from different places?

Here is a typical tailwind.config.js file: module.exports = { content: [ "./pages/**/*.{js,ts,jsx,tsx}", "./components/**/*.{js,ts,jsx,tsx}", ], theme: { extend: {}, }, plugins: [], } Considering the creation of a ...

What is the best way to render components with unique keys?

I am currently working on a dashboard and would like to incorporate the functionalities of React-Grid-Layout from this link. However, I am facing an issue where the components are only rendered if they have been favorited. In order to utilize the grid layo ...

Attention: WARNING regarding the NEXTAUTH_URL in the Development Console

While working on my Next.js web application with next-auth for authentication, I came across a warning message in the development console. The message is related to reloading the environment from the .env.local file and compiling certain modules within the ...

Develop a structured type that encompasses the stationary attributes of an object-oriented class

Provided are the following classes: class EnumerationDTO { designation: string; id: number; } class ExecutionStatusDTO extends EnumerationDTO { static readonly open: ExecutionStatusDTO = { id: 0, designation: 'Open' }; static readonl ...

What is the best way to achieve maximum height?

Currently, I am attempting to obtain the total height of the page in order to apply it to the styles, specifically for the darkMask class. The reason for needing this height is that when a certain action is triggered within the header, a dark overlay is a ...

Exploring the contrast of && and ?? in JavaScript

My current focus is on utilizing the Logical AND && and Nullish coalescing operator ?? in handling conditional rendering of variables and values. However, I find myself struggling to fully comprehend how these operators function. I am seeking clar ...

The compatibility issues between Angular 5 and materialize-css (v 1.0.0) are causing obstacles in functionality

I attempted to implement the solution found on this post: Unfortunately, the solution didn't work as expected. I am working with Angular and Typescript in my project. Here is a snippet of my Typescript class: import { Component, OnInit, AfterVi ...

Using a template reference variable as an @Input property for another component

Version 5.0.1 of Angular In one of my components I have the following template: <div #content>some content</div> <some-component [content]="content"></some-component> I am trying to pass the reference of the #content variable to ...

Something went wrong: "Server Error - No 'exports' main defined in package.json for C:chart ode_moduleschart.js"

I'm attempting to retrieve the time scale (x-axis) by employing the chartjs-adapter-date-fns adapter, but encountering the following error: Error [ERR_PACKAGE_PATH_NOT_EXPORTED]: C:\chart\node_modules\chart.js\package.json does n ...

Deno.Command uses backslashes instead of quotes for input containment

await new Deno.Command('cmd', { args: [ '/c', 'start', `https://accounts.spotify.com/authorize?${new URLSearchParams({ client_id, response_type: 'code', ...

Error encountered in 'Next.js' at '_next/static/YzkQBtj6rd9b69Th7lZs0/pages/index.js' path

Encountering an error in my Next.js project. www.~~~.com/_next/static/YzkQBtj6rd9b69Th7lZs0/pages/index.js net::ERR_ABORTED 404 (Not Found) It seems that I have set up Next.js on www.~~~.com/beta However, it is trying to call root from www.~~~.co ...

What steps should I follow to create a Lunr search functionality for Markdown MD files?

Currently, I am in search of a suitable lunr search implementation for my MD (Markdown) documents spread throughout my React/NextJS website. Our website contains a plethora of Markdown docs within both blog and regular "docs" sections, necessitating a robu ...

Utilizing Observable to dynamically bind ngClass in Angular

I currently have a container with the following structure <mat-sidenav-container [ngClass]="{'sidepanel-opened': ((isSidePanelVisible$ | async) as isSidePanelVisible) == true }"> </mat-sidenav-container> I am trying to u ...

Is it possible to set up TypeScript npm packages to be installed in their original TypeScript format rather than JavaScript for the purpose of examining the source code?

Despite my lack of expertise in the inner workings of how a TypeScript library compiles itself to JavaScript before being placed in the node_modules directory, I have a question: Coming from a PHP background, I am accustomed to being able to explore any l ...

Developing a Next.js shared library

I am looking to create Next.js components as shared components that can be utilized across multiple projects. 1- To get started, I have developed a basic component named "TextBox" located at src/lib/component/TextBox.js: import { useState } from "react"; ...

What could be causing the elements in my array to appear as undefined?

https://i.stack.imgur.com/ze1tx.png I'm stuck trying to understand why I can't extract data from the array. const usedPlatformLog: Date[] = [] users.forEach(el => { usedPlatformLog.push(el.lastUsed) }) console.log(usedPlatformLog) // disp ...

Encountering issues with Typescript when using absolute paths

After updating a forked repository, I noticed that TypeScript is no longer recognizing absolute paths. Surprisingly, I have not made any changes to my tsconfig.json: { "compilerOptions": { "allowJs": true, "allowSyntheticDefaultImports": true, ...

The compatibility issues between bcrypt and Next.js 14.0 are causing functionality errors

I'm currently working on implementing an Infinite scrolling feature for displaying posts. This requires utilizing a client component with the use client directive. However, I've encountered an issue: Module parse failed: Unexpected token (1:0) ...

Moving from Http to HttpClient in Angular4Changeover your Angular4

I recently migrated my Angular app to use the new HttpClient, but I'm encountering some challenges in achieving the same results as before with Http. Can anyone help me out? Here's what I was doing with Http: getAll() { return this.http.get ...