3

There are some environment variables in my .env file that gets updated when some values get updated on the database.

Example:

REACT_APP_FIREBASE_ID=1234567890

When I log this to the console on my react app:

console.log(process.env.REACT_APP_FIREBASE_ID) //this gives "1234567890"

But when the .env file is updated with something else:

Example:

REACT_APP_FIREBASE_ID=9876543210

The log still gives the old value:

console.log(process.env.REACT_APP_FIREBASE_ID) //this still gives "1234567890"

I am using on CRA on dev mode with "npm start"

If I terminate the server and restart it again, I am able to see the correct output to the console. BUT, this doesn't work after "npm run build"

How can I clear the environment cache after the .env file is changed on the Production Mode?

Saurabh
  • 2,655
  • 1
  • 20
  • 47
  • Are you changing the env variable without restarting the react app or you are changing the variable and shut down the app and restart again? – onuriltan Oct 10 '19 at 07:27
  • Changing the env file, and then restarting the server on the dev mode with "npm start". Doing this on the dev mode is fine. We can restart the servers. But how to do that on the production mode? – Saurabh Oct 10 '19 at 07:29
  • Env variables are not meant to be changed without server restart. It is more advisable if you store your data in another place. – Horatiu Jeflea Oct 10 '19 at 07:30
  • @HoratiuJeflea in a JSON file maybe? And update that JSON whenever the database is updated? – Saurabh Oct 10 '19 at 07:32
  • Checking a solution for Google Cloud, I only know for Azure and AWS. – Horatiu Jeflea Oct 10 '19 at 07:33
  • I have came across the same situation, restarting the application every-time when .env file is modified is resolved my issue. – Akhil S Nov 27 '20 at 14:22

1 Answers1

0

This is how I solved it.

My first approach was to get the value from the .env file, but unless the server is restarted, this approach doesn't work. [BAD]

My second thought was to create a JSON file and keep the data from inside that, and update the JSON file whenever the Database is updated. Sadly, this was a very bad approach because CRA (or probably any react project) cannot call a file outside the src folder and after the build, there is no scope to change the built js files. [VERY BAD]

Finally, I managed to solve this using this approach [DECENT, I Guess]

  • Saving the data on a table in a key-value format (You may just save in JSON format too)
  • When the application is loaded (main component is loaded), call an API that gets that key-value(or JSON) and store the data in the LocalStorage of the browser.
  • Get the value on the application with localStorage.getItem("theKeyName")

A Tip: You could check if the key is already present on the LocalStorage before making the API call.

if(localStorage.getItem("theKeyName") !== null) {
    //your API fetch request or redux dispatch
}
Saurabh
  • 2,655
  • 1
  • 20
  • 47