Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nx React inject environment variables at runtime

I have a Nx monorepo with multiple react applications.

I want to be able to run the build once and then deploy the same build to multiple environments (e.g. dev, test, production).

What I used to do in previous projects where I wasn't using Nx, it was to have a env.js file in the /public folder and a script tag in the head of index.html to get the env.js file.

is it possible to achieve the same result with Nx?

like image 645
marinvirdol Avatar asked Apr 02 '26 11:04

marinvirdol


1 Answers

NX by default gives you an /environments/environment.ts file where you can store your environment variables.

You can import it into your app with:

import { environment } from './environments/environment'

You can swap out environments during the build process with the workspace.json file.

...
"configurations": {
  "production": {
    "fileReplacements": [
      {
        "replace": "apps/client/src/environments/environment.ts",
        "with": "apps/client/src/environments/environment.prod.ts"
      }
    ],
  ...

If you want to inject environment variables into your index.html file, you have to actually set those when you're building your app. For local builds,

Locally

I created an .env file at the root of the react project and put the variables there

Hosted Environments

We added the envvars to our CI during the build process.

- name: Build Applications
  run: |
    NX_DOMAIN_NAME="My Super Domain" npx nx run-many --target=build --configuration=production

https://nx.dev/latest/react/guides/environment-variables#using-environment-variables-in-indexhtml

like image 90
VtoCorleone Avatar answered Apr 04 '26 15:04

VtoCorleone



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!