I have a react app hosted as static site under express server project in a folder called client/build. I have some oauth redirect uris that point to express server also points to for token retrieval later. My react-app redirects user to oauth endpoint which my express server env variables also refer to.
` //express .env :
process.env.HOST=localhost
process.env.PORT=port
process.env.OAUTH2URI=example.com
`
` //react .env :
process.env.REACT_APP_HOST=localhost
process.env.REACT_APP_PORT=port
process.env.REACT_APP_OAUTH2URI=example.com
`
when i run my express app, how can the react app refer to the same host and port my express server app is using ?
Can i not refer the common env variables from express app into react app without duplicating with different names.
There's only one gotcha, to access environment variables from the client app they must be prefixed with REACT_APP_ . Otherwise they will only be accessible on the server side. You can access environment variables (with the REACT_APP_ prefix) from your React app via the Node. js process.
I tried a lot of things, of which none seemed to work. What I did as a workaround for this is make an API in Express which will be called by the front-end and will forward the env vars. Something of the sort:
app.get('/getEnvironmentVars', (_, res) => {
res.json({ ENVIRONMENT: process.env })
})
Then you just fetch it in the front-end code like:
export async function getEnvironmentVarsFromExpress() {
return await fetch('/getEnvironmentVars').then((res) => res.json())
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With