Home > other >  How to get environment variables in the aAPI side from the UI?
How to get environment variables in the aAPI side from the UI?

Time:03-23

React noob here. I'm currently migrating an app from Next.js to React.

In Next, we had certain environment variables (such as root URLs) defined in our Jenkinsfile that would be called from our UI via process.env.[var].

Now that we're migrating to React, I can't use process.env in the UI side, as this is a Node property. I also can't store these environment variables on the API side and call them from the UI side, as React doesn't allow references to be made outside the UI's /src directory.

Is there a way to use our environment variables (defined in Jenkinsfile) from our UI? I'm considering creating a GET endpoint in the API side to return the environment variables to the UI when it loads, but would like to know if there are any alternative solutions.

Probably obvious, but here's the basic layout of our app

-api
  -src
-ui/react
  -src
    -utils
      constants.js <- trying to store the env vars here
jenkinsfile

CodePudding user response:

If you are using create-react-app you can define your env variables in the .env file, just prefix them with REACT_APP_.

If not, you can use build tools like webpack to add them for you

CodePudding user response:

Technically, we can't use environment variables in browser context, that's why we usually use DefinePlugin or EnvironmentPlugin in webpack based projects like CRA and Vue-CLI to statically replace process.env.* with environment variables.

But this way will forces us to rebuild the whole application multiple times for different stages.

To fix this, without compromises., I recommend trying import-meta-env.

During production, this plugin statically replaces import.meta.env.* with placeholders (we use import.meta because process.env is a Node specific object), then we can run the built-in script and replace the placeholders with real environment variables later.

I also created an example for Docker. For Jenkins, I think it can be done in the same way.

Hope this helps someone who needs it.

  • Related