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

Having trouble aligning page in the center with flexbox and styled components

Hey there, I'm having some trouble figuring out how to center my page using flexbox within styled components in a Next.js app. Any suggestions or tips? Let me share with you my Blog Component import ReactMarkdown from 'react-markdown' impor ...

Packaging a NodeJS project in Visual Studio - A step-by-step guide to creating and setting up an N

In my VS2013 solution, I have a combination of NodeJS (using TypeScript) and C# class library projects connected by EdgeJS. Among the NodeJS projects, one serves as a library for a RabbitMQ bus implementation, while two are applications meant to be hosted ...

The logic for children in Next.js layout is executed before any redirections take place

In my Next.js 13 app, I use the app router to redirect users to the login page if they are not logged in. This redirection is done in the layout.tsx file located in a page folder. Essentially, I want to determine if the user is logged in before rendering o ...

Unable to submit data to PHP script using Angular 2

I am currently attempting to send a post request to a PHP script that contains the necessary data I require. Within home.component.ts: import { Component, OnInit } from '@angular/core'; import { UserComment } from '../definition/us ...

What is the return type of the Array.prototype.sort() method in Typescript?

I have created a custom type for arrays that are considered "sorted" like this: type Sorted<T> = T[]; This serves as a reminder for developers to provide a sorted array of any type and ensure the sorting themselves. Although I understand that Types ...

What is the best method to retrieve HTTP headers from the backend and simultaneously send HTTP parameters to it in ASP.NET Core and Angular?

I am currently working with Angular 15 and ASP.NET Core 5. The backend retrieves paged items based on the parameters pageSize and pageIndex. Once the action method receives the pageSize and pageIndex parameters, it sends both the paged items and the total ...

The trouble with React Navigation encountered with TypeScript: This Entity Cannot Be Invoked

Currently, I'm facing a typescript issue after upgrading to React Navigation 5. The specific error message reads: There is an issue with calling this expression. The union type '{ <RouteName extends "Stack1Screen1" | "Home&quo ...

What is the best way to send a useState value to getServerSideProps in Nextjs?

Hello everyone, I've been working on this for 4 hours now trying to filter a product. I have set the state upon onClick event. I am struggling to figure out how to change the query. Here is my code: export async function getServerSideProps() { awa ...

Tips for stopping TypeScript code blocks from being compiled by the Angular AOT Webpack plugin

Is there a way to exclude specific code from Angular's AOT compiler? For instance, the webpack-strip-block loader can be utilized to eliminate code between comments during production. export class SomeComponent implements OnInit { ngOnInit() { ...

Transforming a JavaScript chained setter into TypeScript

I have been utilizing this idiom in JavaScript to facilitate the creation of chained setters. function bar() { let p = 0; function f() { } f.prop = function(d) { return !arguments.length ? p : (p = d, f); } return f; } ...

Bug in auto compilation in Typescript within the Visual Studios 2015

Currently, I am utilizing Visual Studio Pro 2015 with auto compile enabled on save feature. The issue arises in the compiled js file when an error occurs within the typescript __extends function. Specifically, it states 'Cannot read property prototyp ...

Troubleshooting issue with jest expect.any() failing to work with a custom class following migration from JavaScript to TypeScript

I recently made the switch to TypeScript in my project, and now some of my Jest tests are failing. It appears that the next function below is no longer being called with an AppError object, but with an Error object instead. Previously, the assertion expec ...

Troubleshooting problem in React component: `background-repeat` is not functioning as expected

I'm having a problem with the background-repeat CSS property in my React component. I've set the backgroundRepeat property to "repeat," but it's not working as expected. The background image is not repeating like it should. Here is the style ...

Error: Unable to locate module: 'cats.png' in the '/public/img' directory within Next.js

I am trying to implement the img tag in my Next app, but it doesn't seem to be working. This is how I have coded the img tag: <img src={'/public/img/cats.png'} alt="cats img" /> Despite searching extensively, I have been una ...

Implementing Immer in Typescript

Recently, I've been exploring the possibility of integrating Immer into my React project that already utilizes Typescript. Unfortunately, I haven't been able to discover a clear guide on how to effectively employ Immer in conjunction with Typescr ...

A Guide to Retrieving Parameters and Request Body using Express and Typescript

When I use the PUT method, I encounter this issue: const createFaceList = (req: Request<{faceListId : string}>, res: Response, next: NextFunction) => { console.log(req.body.name); console.log("faceListID = " + req.params.faceListId); a ...

Can you explain the significance of the | symbol in TypeScript?

My journey with TypeScript is just beginning, and I recently encountered the symbol | while working on a problem in LeetCode using Typescript. I believe it has something to do with defining variable types. Can anyone provide more insight into this? /** ...

String Compression - Number of Elements

Suppose I define a specific type: type SomeType = 'a' | 'b' | 'c' Is there a TypeScript function available that can calculate the number of unique values a variable of type SomeType can hold? assertEq(countUniqueValues(SomeTy ...

Tips for utilizing Provide/Inject in Vue.js while leveraging TypeScript

I am currently working with Vue.js and TypeScript along with the vue-property-decorator package. The documentation suggests that I can achieve something like this: import { Component, Inject, Provide, Vue } from 'vue-property-decorator' const s ...

What could be causing the "ERROR TypeError: Cannot read property 'length' of undefined" message to occur with a defined array in my code?

Even though I defined and initialized my array twice, I am encountering a runtime error: "ERROR TypeError: Cannot read property 'length' of undefined." I have double-checked the definition of the array in my code, but Angular seems to be playing ...