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.
Set Environment Variables
Section titled “Set Environment Variables”By default, Nx will load any environment variables you place in the following files:
apps/my-app/.env.[target-name].[target-configuration-name].localapps/my-app/.env.[target-name].[target-configuration-name]apps/my-app/.env.[target-name].localapps/my-app/.env.[target-name]apps/my-app/.[target-name].[target-configuration-name].local.envapps/my-app/.[target-name].[target-configuration-name].envapps/my-app/.[target-name].local.envapps/my-app/.[target-name].envapps/my-app/.env.localapps/my-app/.local.envapps/my-app/.env.env.[target-name].[target-configuration-name].local.env.[target-name].[target-configuration-name].env.[target-name].local.env.[target-name].[target-name].[target-configuration-name].local.env.[target-name].[target-configuration-name].env.[target-name].local.env.[target-name].env.env.local.local.env.env
Environment Variables for Configurations
Section titled “Environment Variables for Configurations”Nx will only load environment variable files for a particular configuration if that configuration is defined for a task, even if you specify that configuration name from the command line. So if there is no development configuration defined for the app's build task, the following command will use .env.build instead of .env.build.development:
nx build app --configuration developmentIn order to have Nx actually use the .env.build.development environment variables, the development configuration needs to be set for the task (even if it is empty).
{ "targets": { "build": { // ... "configurations": { "development": {} } } }}Point to Custom Env Files
Section titled “Point to Custom Env Files”If you want to load variables from env files other than the ones listed above:
- Use the env-cmd package:
env-cmd -f .qa.env nx serve - Use dotenvx:
dotenvx run --env-file=.qa.env -- nx serve - Use the
envFileoption of the run-commands builder and execute your command inside of the builder
Ad-hoc Variables
Section titled “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_PUBLIC_API_URL=http://localhost:3333 nx build myappWindows (cmd.exe)
set "NX_PUBLIC_API_URL=http://localhost:3333" && nx build myappWindows (Powershell)
($env:NX_PUBLIC_API_URL = "http://localhost:3333") -and (nx build myapp)