Home > Back-end >  Typescript class does not recognize constants in .env file, but recognizes them in a React component
Typescript class does not recognize constants in .env file, but recognizes them in a React component

Time:09-26

I am using .env file and reading from it. I use it like this: process.env.BASE_URL in both the class and the react component. Why would it work in the component and in the class it is undefined?

This is the class and here the value of process.env.BASE_URL is undefined:

export default class HttpClient {
  async prepareFileForSigning(file: string) {
    var request = {
      data: file,
    };

    const res = await axios
      .post<GetAttachmentsResponse, AxiosResponse<any>>(process.env.BASE_URL   "/something", request)
      .catch(function (err) {
        console.log(err.response.data.info);
        NotificationManager.error(
          err.response.data.info ?? t("notifications.serverError"),
          t("notifications.error"),
          3000
        );
      });
    return (res as any).data;
  }
}

This is the React component and here the value of process.env.CLIENT_ID and the rest is good:

export const ChooseSign: React.FC<AppProps> = (props) => {

        var request = {
          client_id: process.env.CLIENT_ID,
          client_secret: process.env.CLIENT_SECRET,
          scope: process.env.SCOPE,
          grant_type: process.env.GRANT_TYPE,
          requested_token_use: process.env.REQUESTED_TOKEN_USE,
          assertion: res,
        };

        //rest of the code
};

export default ChooseSign;

This is my .env file:

# prod
# CLIENT_ID=############
# CLIENT_SECRET=############
# CONSENT_URL=############
# dev
CLIENT_ID=############
CLIENT_SECRET=############
CONSENT_URL=############
#
SCOPE=user.read contacts.read mail.read email offline_access openid profile
GRANT_TYPE=urn:ietf:params:oauth:grant-type:jwt-bearer
REQUESTED_TOKEN_USE=on_behalf_of
#
BASE_URL=############
BASE_URL_GRAPH=############
BASE_URL_MICROSOFT_ONLINE=############
#
NODE_ENV=development
PORT=3007

What could I do?

CodePudding user response:

You can either define a default value for the environment variable in the URL:

const res = await axios
      .post<GetAttachmentsResponse, AxiosResponse<any>>((process.env.BASE_URL || "default URL")   "/something", request)

Or define environment variable types in an environment.d.ts file, check this answer for more.

The values in ChooseSign are good because you are defining a new object, so the string values can be of type string | undefined.
On the other hand, the axios call requires a string.

  • Related