how to share environment variables between react app and express js server hosting it as static site

Viewed 1900

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.

2 Answers

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())
}
Related