Environment Variables not available in index.html for webpack 5 builds (React)
See original GitHub issueCurrent Behavior
In the NX docs, it states that you can access the environment variables in the index.html file like so:
https://nx.dev/latest/react/guides/environment-variables#using-environment-variables-in-indexhtml
For a react app that uses webpack 5, this is not the case. It does not replace the placeholder with the environment variable in the .env file.
Expected Behavior
The environment variables should be injected into the index.html folder at build time.
Steps to Reproduce
- Create a new NX repo with a react app:
npx create-nx-workspace@latest - In the react app, add a
.envfile with a variable in e.g.NX_TEST_VARIABLE='xyz' - In the
index.htmlfile add the following tag to the body:<p>%NX_TEST_VARIABLE%</p> - Run
nx serve app- observe that the env variable is populated on the screen - Now upgrade from webpack 4 to webpack 5
npx nx g @nrwl/web:webpack5 - Run
nx serve appagain - observe that now the env var is not populated and you see:%NX_TEST_VARIABLE%instead
Failure Logs
No visible failure logs
Environment
NX report: Node : 14.17.3 OS : darwin x64 npm : 7.20.0
nx : Not Found @nrwl/angular : Not Found @nrwl/cli : 12.8.0 @nrwl/cypress : 12.8.0 @nrwl/devkit : 12.8.0 @nrwl/eslint-plugin-nx : 12.8.0 @nrwl/express : Not Found @nrwl/jest : 12.8.0 @nrwl/linter : 12.8.0 @nrwl/nest : Not Found @nrwl/next : Not Found @nrwl/node : Not Found @nrwl/nx-cloud : Not Found @nrwl/react : 12.8.0 @nrwl/schematics : Not Found @nrwl/tao : 12.8.0 @nrwl/web : 12.8.0 @nrwl/workspace : 12.8.0 @nrwl/storybook : 12.8.0 @nrwl/gatsby : Not Found typescript : 4.3.5
Issue Analytics
- State:
- Created 2 years ago
- Comments:15 (4 by maintainers)

Top Related StackOverflow Question
I’m not really sure how to fix the issue. But we created a workaround for our project since we needed some conditional rendering in our
index.html(scripts injected if env variable is defined and so on). Maybe it could fit your needs as well.webpack.config.jsin your apps root folder:With this you can use ejs template stuff in your index.html file:
Thank you for investigating this @jaysoo!