user968437
user968437

Reputation: 103

process.env environment variable undefined

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?

Upvotes: 7

Views: 19399

Answers (5)

somayeh
somayeh

Reputation: 1

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

Try restarting your application:

npm start

Upvotes: 0

Hritik Sharma
Hritik Sharma

Reputation: 2010

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.

Upvotes: 4

MwamiTovi
MwamiTovi

Reputation: 2502

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!

Upvotes: 10

user968437
user968437

Reputation: 103

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

Upvotes: 0

chenc
chenc

Reputation: 331

You can use this package to defined the process env

cross-env

Upvotes: 0

Related Questions