Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 410
Full Stack Brain Avatar asked Mar 10 '20 22:03

Full Stack Brain


People also ask

How do you access system environment variables in react JS?

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.


1 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())
}
like image 132
Pero93 Avatar answered Oct 04 '22 21:10

Pero93