55

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.

2
  • 1
    you can't, use js to make a script element... Commented Mar 20, 2018 at 3:29
  • check my updated answer + example below... Commented Mar 20, 2018 at 5:47

5 Answers 5

27

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.

Sign up to request clarification or add additional context in comments.

1 Comment

20

Solution

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.

HtmlWebpackPlugin

Simplifies creation of HTML files to serve your webpack bundles.

You can either let the plugin generate an HTML file for you, supply your own template using lodash templates or use your own loader.

Webpack.config.js

HtmlWebpackPlugin allows you to create and pass parameters to your template:

   const api_key = process.env.api_key;
   const HtmlWebpackPlugin = require('html-webpack-plugin');
    
    module.exports = {
      entry: 'index.js',
      plugins: [
        new HtmlWebpackPlugin({
          inject: false,
          template: './template.html',

          // Pass the full url with the key!
          apiUrl: `https://maps.googleapis.com/maps/api/js?key=${api_key}`,

        });
      ]
    }

template.html

Inside the template you can access to the parameter:

<script src="<%= htmlWebpackPlugin.options.apiUrl %>"></script>

See: Writing Your Own Templates

Notes

This is a modified answer from this comment, please read the full conversation.

6 Comments

Thank you. I'm still not clear. Where do I add your code? I tried putting all of it in between the <script type="text/javascript"></script> tags but I get "Reference error: process is not defined." I added the index.html above.
you can access to process from your webpack.config right?
I've access process in webpack.config by 'process.env.NODE_ENV.' Also, I have accessed process.env in another API call in a .js file. The problem is just accessing in index.html.
I put the following code in componentWillMount where the map renders and it worked (at least in development: const API_KEY = process.env.GOOGLEMAP_API_KEY; const script = document.createElement('script'); script.src = https://maps.googleapis.com/maps/api/js?key=${API_KEY}; document.head.append(script);
How to access htmlWebpackPlugin.options.apiUrl this variable inside script like this <script> const some_variable = htmlWebpackPlugin.options.apiUrl; if(some_variable) { do something } </script> . Another question is like how does <script src="<%= htmlWebpackPlugin.options.apiUrl %>"></script> here show does this syntax works I mean htmlWebpackPlugin how do we get this variable context here.
|
15

The simple way you can use

in HTML

<p>%NODE_ENV%</p>

and in script

<script>
if('%NODE_ENV%' === 'production') {
.... some code
}
</script>

1 Comment

That didn't work for me
2

I put the following code in componentWillMount where the map renders and it worked (at least in development: const API_KEY = process.env.GOOGLEMAP_API_KEY; const script = document.createElement('script'); script.src = https://maps.googleapis.com/maps/api/js?key=${API_KEY}; document.head.append(script);

I was able to get this to work using the code posted by bigmugcup in the comments above. I did not modify the webpack.config.js file.

Comments

2

I was looking for the issue how to set attribute value conditionally, after a couple of minutes, I actually found a way to handle this case, which I am listing below. And its handled by HtmlWebpackPlugin. This snippet will also help you referencing environment variable in HTML file.

Environment setup

  • I am using Create React App, which has HtmlWebpackPlugin within modules, will be visible upon ejecting the application.
  • My App is in default state i-e not ejected

Environment Variable Definition

I am setting environment variable [APP_ENV] in scripts property of Package.json file., which looks like

"scripts": {
    "start": "set APP_ENV=development&& react-scripts start",
    "build:prod": "set APP_ENV=production&& react-scripts build",
    "eject": "react-scripts eject"
  }

Referencing varialble in HTML file

<link rel="stylesheet" href="https://<%= process.env.APP_ENV ==='production' ? 'prod.domain': 'dev.domain'%>/main.min.css" />

1 Comment

I have a <script> tag in the <head> of my index.html and I'm writing code inside it. How would I reference process.env from there? When I do I get process is not found

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.