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.
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.
You can access environment variables (with the REACT_APP_ prefix) from your React app via the Node. js process. env. object.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With