1

In my React application I use some environmental variables that are going to be changed from time to time. I noticed that after running 'npm run build', all environmental paths get hardcoded. E.g. const server_address = process.env.REACT_APP_SERVER_ADDRESS; becomes REACT_APP_SERVER_ADDRESS:"http://192.168.42.135:3000

Is there any way to still use the environmental variables in deployment after the build?

4
  • No, if you need a variable that changes dynamically "from time to time," you should create a variable in your app that changes based on some actions. You don't have access to process.env, which is only accessible server-side, once you build your app that runs client-side. Commented Feb 1, 2021 at 14:00
  • i think there is a missunderstanding.I don't want to enable user to modify the variables, but the web server administrator. For example, the app will be deployed in different networks, so I'd like to adjust the server address by modifying the .env and restarting the web server, as it was possible before build using npm start. Commented Feb 1, 2021 at 14:14
  • Did you try this -> medium.com/@ferie/… ?? Its for angular but I think you can use it Commented Feb 1, 2021 at 14:21
  • @uppercut then you need to generate a new build that uses the appropriate values for environment variables. You cannot do what you're asking for - once the client-side code is generated and it runs client-side it has no access to the server-side environment variables. Commented Feb 1, 2021 at 14:46

1 Answer 1

1

To address directly, Javascript cannot access Env variable of the OS you are executing it on, Once React is compiled and JS is generated, that's it, no more access to variables from Environment, also access are not really given to React in compilation, but to the transpiler or bundler which runs on node (Node always have access:-) ). But some solutions are here

  1. API That returns latest secret whenever it's called.
  2. Socket pushes new secret to app whenever secret changes.

Happy Coding Comrade :-)

Sign up to request clarification or add additional context in comments.

3 Comments

I think that the author doesn't want to use the .env that is on the user's computer, but on the web server.
Pushing secrets like that is a not a great idea and a huge security risk. What the OP is asking for is not possible without creating a new build per environment.
@goto1 agreed, its risk, but can be a token or something else.....which cannot be compromised

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.