The server has access to an environment variable that is not available on the client, despite being properly prefixed

In my project, I have a file named .env.local that contains three variables:

NEXT_PUBLIC_MAGIC_PUBLISHABLE_KEY=pk_test_<get-your-own>
MAGIC_SECRET_KEY=sk_test_<get-your-own>
TOKEN_SECRET=some-secret

These variables are printed out in the file pages/login.ts:

import UserAuthenticationPage from 'client/features/user-authentication/user-authentication-container';
import redirectIfLoggedIn from 'client/hocs/redirect-if-logged-in';
import { NextPage } from 'next';

(UserAuthenticationPage as NextPage).getInitialProps = async () => {
  console.log('env in login.ts getInitialProps', process.env);
  return {
    namespacesRequired: ['common', 'user-authentication'],
  };
};
console.log('env in login.ts client side', process.env);

export default redirectIfLoggedIn('/')(UserAuthenticationPage);

The above code results in the following output:

env in login.ts getInitialProps {
  __NEXT_PROCESSED_ENV: 'true',
  NEXT_PUBLIC_MAGIC_PUBLISHABLE_KEY: 'pk_test_BD092E437FE31429',
  MAGIC_SECRET_KEY: 'sk_test_C02E14264C276A40',
  TOKEN_SECRET: 'my-secret-token-thingy'
}

On the server side, and:

env in login.ts client side {}

On the client side. Additionally, when running next dev, I also see the message

Loaded env from /Users/dev/my-nextjs-project/.env.local
.

I am wondering why the public environment variables are not being exposed to the browser?

Answer №1

Thanks to JonRSharpe's suggestion, I successfully resolved this issue by utilizing the publicRuntimeConfig method.

import getConfig from 'next/config';

/**
 * @param key The key of the environment variable you want to retrieve.
 * @throws Throws an error if the environment variable is not found.
 * @returns The value of the specified environment variable.
 */
function getEnvironmentVariable(key: string, checkRuntime = false) {
  const variable = process.env[key];

  if (variable) {
    return variable;
  }

  if (checkRuntime) {
    const { publicRuntimeConfig } = getConfig();
    const runtimeVariable = publicRuntimeConfig[key];

    if (runtimeVariable) {
      return runtimeVariable;
    }
  }

  throw new Error(`Missing environment variable for key: ${key}.`);
}

export default getEnvironmentVariable;

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

Sending an event from a child component to another using parent component in Angular

My form consists of two parts: a fixed part with the Save Button and a modular part on top without a submit button. I have my own save button for performing multiple tasks before submitting the form, including emitting an Event to inform another component ...

What is the best method to adjust the width of the PrimeNG ConfirmDialog widget from a logic perspective

Currently utilizing "primeng": "^11.2.0" and implementing the ConfirmDialog code below this.confirm.confirm({ header: 'Announcement', message: this.userCompany.announcement.promptMsg, acceptLabel: this.userCompany.announcement ...

Can you explain the distinction between using tsserver and eslint for linting code?

As I work on setting up my Neovim's Native LSP environment, a question has arisen regarding JS/TS linter. Could someone explain the distinction between tsserver and eslint as linters? I understand that tsserver is a language server offering features ...

Having trouble fetching data from Google's real-time database in a Next.js application

I am currently facing an issue with retrieving data from Google Realtime Database, and I am unsure of where the problem lies. The code snippet below is part of my Categories page: import CategoryHeader from '../../components/CategoryHeader'; impo ...

What is the contrast between element.getAttribute() value and a String in protractor?

When using protractor and typescript, I need to verify that the text saved in a textbox matches a certain string by comparing it with the resulting value of element.getAttribute("value"). Unfortunately, getText() does not work for this scenario b ...

It appears that Jest is having trouble comprehending the concept of "import type"

We've just completed a major update to our monorepository, bringing it up to date with the following versions: Nx 14.3.6 Angular 14.0.3 Jest 28.1.1 TypeScript 4.7.4 Although the compilation process went smoothly after the upgrade, we encountered num ...

Guide to integrating MPA frontend with SSR backend using Next.js?

I recently purchased an MUI template for my project. Utilizing React with Next.js and Flask as the backend, the MUI template functions as a Multiple-Page Application. In the past, I have utilized Flask for a Single Page Application by simply using return s ...

What is the reason for the manual update of a view when copying an object's attributes into another object, as opposed to using Object.assign()?

In my application, I have a parent component called 'EmployeeComponent' that is responsible for displaying a list of employees. Additionally, there is a child component named 'EmployeeDetailComponent' which displays the details of the s ...

Explore the capabilities of the Angular Ng2SearchPipeModule to enhance your search input

I used the ng2SearchPipeModule for an input search, but it's not working. I can't seem to find my error. In my HTML, all my books are within divs. Will typing a book title display all the divs? Of course, I have imported in app.module.ts Ng2Sear ...

Bring in all subdirectories dynamically and export them

Here is what I currently have: -main.js -routeDir -subfolder1 -index.js -subfolder2 -index.js ... -subfolderN -index.js Depending on a certain condition, the number of subfolders can vary. Is there a way to dynam ...

When using Angular's .navigateByUrl() method, it successfully navigates to the desired page, however the html content is not

Whenever I try to navigate to the home page after logging in, I encounter an issue. I have a navbar <app-header></app-header> with two links - one for signing up and another for logging in. After successfully logging in, my goal is to navigate ...

Backend communication functions seamlessly within the service scope, yet encounters obstacles beyond the service boundaries

I'm facing an issue with accessing data from my backend. Although the service successfully retrieves and logs the data, when I try to use that service in a different module, it either shows "undefined" or "Observable". Does anyone have any suggestions ...

What is the best way to retrieve the page slug within the layout file in Next.js, specifically when using the app folder structure?

In my latest project, I have implemented a nested layout using the new app folder. Within this layout, I have included a header that appears across all pages in the path www.mysite.com/some-slug. One issue I am facing is with the signup button located in t ...

The necessity of the second parameter, inverseSide property in TypeORM's configurations, even though it is optional

As I delve into learning Typescript and TypeORM with NestJS simultaneously, a recent use-case involving the OneToMany and ManyToOne relation decorators caught my attention. It seems common practice for developers to include the OneToMany property as the se ...

How can TypeORM be used to query a ManyToMany relationship with a string array input in order to locate entities in which all specified strings must be present in the related entity's column?

In my application, I have a User entity that is related to a Profile entity in a OneToOne relationship, and the Profile entity has a ManyToMany relationship with a Category entity. // user.entity.ts @Entity() export class User { @PrimaryGeneratedColumn( ...

Angular 8 Refresh Token Implementation

I am currently working on an Angular 8 app that is integrated with .NET Core. My goal is to find a way to refresh a JWT token within the application. Within the integration, users are able to validate and receive a token which expires after 30 minutes. T ...

Where do Next.js Server Actions take place?

Can you shed some light on the execution of Next.js Server Actions? The documentation is quite vague, simply mentioning "the server". I am specifically interested in understanding how Next.js Server Actions (using the app router) are executed, as opposed ...

Issue encountered in TypeScript: Property 'counter' is not found in the specified type '{}'.ts

Hey there, I'm currently facing an issue while trying to convert a working JavaScript example to TypeScript (tsx). The error message I keep encountering is: Property 'counter' does not exist on type '{}'.ts at several locations wh ...

Tips on preventing duplication of APIs when retrieving data using nextjs

In my code, I have a function that can be called either from server-side rendering or client side: export const getData = async (): Promise<any> => { const response = await fetch(`/data`, { method: 'GET', headers: CONTENT_TYPE_ ...

Guide on linking enum values with types in TypeScript

My enum type is structured as follows: export enum API_TYPE { INDEX = "index_api", CREATE = "create_api", SHOW = "show_api", UPDATE = "update_api", DELETE = "destroy_api" }; Presently, I have a f ...