6

I am trying to access an environment variable through process.env in my React/Typescript code, but it's returning undefined. I am able to access NODE_ENV though.

console.log(process.env.CURRENT_URL) // prints "undefined" on browser
console.log(process.env.NODE_ENV) // prints "development" on browser

CURRENT_URL is present in windows environment variable.

Why is process.env.NODE_ENV is accessible but not the other variable?

MwamiTovi
  • 2,425
  • 17
  • 25
user968437
  • 93
  • 1
  • 1
  • 4
  • Are you using create-react-app? – Gabriel Lobo Feb 17 '22 at 02:08
  • Looks like whatever React framework you are using defines NODE_ENV by default while you are doing something wrong to define your custom environment variables. – A Webb Feb 17 '22 at 02:09
  • It’s a plugin in https://backstage.io/ app. I can access CURRENT_URL in node through command line . The issue is happening inside the code only. – user968437 Feb 17 '22 at 02:26

5 Answers5

8

This is your answer, from the official create-react-app docs.

Summary:
By default you will have NODE_ENV defined for you, and any other environment variables starting with REACT_APP_.

So prepend REACT_APP_ to all your env variables e.g. REACT_APP_CURRENT_URL.
That should work!

Neil
  • 7,861
  • 4
  • 53
  • 74
MwamiTovi
  • 2,425
  • 17
  • 25
1

As you are on a react project, you would have to prepend the env variables with REACT_APP_.

You can follow those steps:

  • Provide a variable in your .env file which start with REACT_APP_ (e.g: REACT_APP_MY_VAR).
  • Then, in your code, you can get it using process.env (e.g: process.env.REACT_APP_MY_VAR).

Example:

Define the variables in .env file

REACT_APP_PASSWORD=1234
REACT_APP_LANGUAGE=english

How to use the environment variables?

console.log(process.env.REACT_APP_LANGUAGE);

// output: english

Don't forget to restart the application when you add a new environment variable.

Hritik Sharma
  • 1,756
  • 7
  • 24
0

You can use this package to defined the process env

cross-env

chenc
  • 331
  • 1
  • 5
0

The issue was being caused by backstage software configuration, which was blocking the frontend plugin from accessing variables. I had to explicitly expose the variables to my frontend plugin using - backstage visibility keyword

Harsh Patel
  • 6,334
  • 10
  • 40
  • 73
user968437
  • 93
  • 1
  • 1
  • 4
0

I had the same problem also but when I restart(with npm start) my project it works!

Try restarting your application:

npm start
Hritik Sharma
  • 1,756
  • 7
  • 24