Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you reference a process.env variable in HTML <script src="" ? React

I have a react app and am using dotenv-webpack to manage my API keys.

I have: - created a .env with the API keys and gitignored it. - required and added dotenv as a plugin in webpack.config.js.

After that, I've been able to reference one of the keys in a .js file by using process.env.api_key. But I am having problems trying to reference it in index.html in the script tag.

index.html:

<!DOCTYPE html> <html>   <head>     <meta name="viewport" content="width=device-width, initial-scale=1">     <link rel="stylesheet" href="/style/style.css">     <link rel="stylesheet" href="https://cdn.rawgit.com/twbs/bootstrap/48938155eb24b4ccdde09426066869504c6dab3c/dist/css/bootstrap.min.css">     <script src="https://maps.googleapis.com/maps/api/js?key=process.env.GOOGLEMAP_API_KEY"></script>   </head>   <body>     <div class="container"></div>   </body>   <script src="/bundle.js"></script> </html> 

How do I reference the process.env.API_key here?

<script src="https://maps.googleapis.com/maps/api/js?key=[API_KEY]"></script> 

I have tried using backquotes that work in .js file, like so ${API_KEY}, but that does not work in the .html file.

like image 740
bigmugcup Avatar asked Mar 20 '18 03:03

bigmugcup


People also ask

How do you reference a process env variable in HTML?

You can't reference the process. env variable directly inside html . Create your own template from index. html and replace the api url with a parameter.

How do I view a .env variable in React?

You can access environment variables (with the REACT_APP_ prefix) from your React app via the Node. js process. env. object.


1 Answers

If you're already using create-react-app, this is already available by updating to

<script src="https://maps.googleapis.com/maps/api/js?key=%REACT_APP_API_KEY%"></script> 

as it says in the docs

You can also access the environment variables starting with REACT_APP_ in the public/index.html.

like image 147
Taku Avatar answered Sep 19 '22 20:09

Taku