Define Environment Variables

Environment variables are global system variables accessible by all the processes running under the Operating System (OS). Environment variables are useful to store system-wide values such as the directories to search for executable programs (PATH), OS version, Network Information, and custom variables. These env variables are passed at build time and used at the runtime of an app.

This guide is divided into two sections:

Setting environment variables

By default, Nx will load any environment variables you place in the following files:

  1. apps/my-app/.[target-name].env
  2. apps/my-app/.env.[target-name]
  3. apps/my-app/.local.env
  4. apps/my-app/.env.local
  5. apps/my-app/.env
  6. .[target-name].env
  7. .env.[target-name]
  8. .local.env
  9. .env.local
  10. .env

Pointing to custom env files

If you want to load variables from env files other than the ones listed above:

  1. Use the env-cmd package: env-cmd -f .qa.env nx serve
  2. Use the envFile option of the run-commands builder and execute your command inside of the builder

Ad-hoc variables

You can also define environment variables in an ad-hoc manner using support from your OS and shell.

Unix systems

In Unix systems, we need to set the environment variables before calling a command.

Let's say that we want to define an API URL for the application to use:

NX_API_URL=http://localhost:3333 nx build myapp

Windows (cmd.exe)

set "NX_API_URL=http://localhost:3333" && nx build myapp

Windows (Powershell)

($env:NX_API_URL = "http://localhost:3333") -and (nx build myapp)