Nx React inject environment variables at runtime

Viewed 4888

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?

2 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

Set variable prefixed with NX_ into your .env file:

NX_SERVER_URL=http://localhost:8080

Then it will be accessable within your react app:

const url = process.env.NX_SERVER_URL

Or in html document:

<p>The server url is %NX_SERVER_URL%.</p>

Also NX docs

Related