Disclaimer: I am a React noob so perhaps what I am trying to do is not the React Way
I am writing a React front-end that will be deployed to be served statically by some cloud provider, e.g. S3 or Google Storage or whatever. This front-end interacts with several API servers that live somewhere in the cloud, maybe in the same provider, maybe not. Furthermore, while developing the UI or part of it, those servers' addresses might be local or testing instances.
How do I inject the API server(s) URLs into my react application in a flexible so that I can deploy in dev, staging or prod using different addresses?
SOLUTION: I finally ended up using a combination of solutions proposed:
- use
.env.productionand.env.developmentfiles (exact names) to store the variableREACT_APP_API_URI = 'host' - this is automatically picked-up by create-react-app's build scaffolding and available in UI code as
process.env.REACT_APP_API_URI
Note this somewhat goes against principles from 12 Factor Apps, e.g. storing env variables in files in version control but it does the job ATM.
.env.sampleto the repo not the actual files with values. Also, you can probably set that environment variable in your CI/CD to better align with the 12 Factor approach.console.log(process.env.NODE_ENV)andconsole.log(process.env.REACT_APP_API_URI)to watch from any place after adding.env.productionand.env.developmentfiles to root dir.create-react-app, you need to prefixREACT_APP_to the variable name to be able to access it.Terminate batch job (Y/N)? y, thennpm start. I couldn't figure out for the life of me what I was missing