Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I access an environment variable from within the public folder?

In my create-react-app app I have a javascript file in my public folder. Within it, I need to access an environment variable named REACT_APP_ACTUAL_ENV but I'm not sure how I can. Trying the usual process.env.REACT_APP_ACTUAL_ENV doesn't work because process is undefined in the public folder. Looking at https://facebook.github.io/create-react-app/docs/adding-custom-environment-variables, I can do %REACT_APP_ACTUAL_ENV% within an HTML file in the public folder and it works just fine. But the problem is I need to do this within a javascript file somehow, though I'm not sure if it's possible.

like image 845
Jonah Avatar asked Jul 14 '19 22:07

Jonah


People also ask

How do I get to environment variables?

On the Windows taskbar, right-click the Windows icon and select System. In the Settings window, under Related Settings, click Advanced system settings. On the Advanced tab, click Environment Variables.

What is the command to see environment variables?

To list all the environment variables, use the command " env " (or " printenv "). You could also use " set " to list all the variables, including all local variables.

Can a browser access environment variables?

Accessing Environment Variables in the browser.By default, environment variables are only available in Node. js code and are not available in the browser as some variables should be kept secret and not exposed to anyone visiting the site.


1 Answers

In my case, I have to reference REACT_APP_FACEBOOK_APP_ID environment variable to initialize Facebook SDK inside public/index.html file.

I simply assign the variable to HTML element's property then access it using JavaScript like so:

...
<meta property="fb:app_id" content="%REACT_APP_FACEBOOK_APP_ID%" />

<script>
   const facebookAppId = document.querySelector('[property="fb:app_id"]').content;
   // use `facebookAppId` here
</script>

like image 166
bertdida Avatar answered Nov 01 '22 08:11

bertdida