[Tips] How to Access Environment Variables Stored in .env from index.html in your React Project
Case Study
My current project required to embed Google Analytics tags in React project's index.html
for two different environments, DEV and STG respectively.
Solution
Create a .env
file for each environment.
In order to follow the naming convention for environment variables in React, you need to prefix them with REACT_APP
as examples below.
.env.development
REACT_APP_GA_TAG_MANAGER_ID=GTM-N34****
.env.stg
REACT_APP_GA_TAG_MANAGER_ID=GTM-KFD****
Update index.html
Then in your index.htm
file where you want to refer to the environment variable, you refer to it as a string in the form %<variable name>%
.
index.html
<!DOCTYPE html> <html lang="en"> <head> <!-- ...meta tags and styles are omitted --> <!-- Google Tag Manager --> <script> (function (w, d, s, l, i) { w[l] = w[l] || []; w[l].push({"gtm.start": new Date().getTime(), event: "gtm.js"}); var f = d.getElementsByTagName(s)[0], j = d.createElement(s), dl = l != "dataLayer" ? "&l=" + l : ""; j.async = true; j.src = "https://www.googletagmanager.com/gtm.js?id=" + i + dl; f.parentNode.insertBefore(j, f); })( window, document, "script", "dataLayer", "%REACT_APP_GA_TAG_MANAGER_ID%", ); </script> <!-- End Google Tag Manager --> </head> <body> <!-- Google Tag Manager (noscript) --> <noscript ><iframe src="https://www.googletagmanager.com/ns.html?id=%REACT_APP_GA_TAG_MANAGER_ID%" height="0" width="0" style="display:none;visibility:hidden" ></iframe ></noscript> <!-- End Google Tag Manager (noscript) --> <div id="root"></div> </body> </html>
Result
DEV Environment:
STG Environment:
It's a little hard to see in screenshots, but now you can see that the index.html
of the DEV environment has tags starting with GTM-N34
embedded and the STG environment has tags starting with GTM-KFD
embedded as expected.
Original Post
Japanese version of this article is also available here.