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.
Setting environment variables
By default, Nx will load any environment variables you place in the following files:
Nx will move through the above list, ignoring files it can't find, and loading environment variables into the current process for the ones it can find. If it finds a variable that has already been loaded into the process, it will ignore it. It does this for two reasons:
- Developers can't accidentally overwrite important system level variables (like
- Allows developers to create
.local.envfiles for their local environment and override any project defaults set in
- Allows developers to create target specific
.[target-name].envto overwrite environment variables for specific targets. For instance, you could increase the memory use for node processes only for build targets by setting
- Nx will first load the variables from
apps/my-app/.env.localinto the process. When it tries to load the variables from
apps/my-app/.env, it will notice that
NX_API_URLalready exists, so it will ignore it.
We recommend nesting your app specific
env files in
apps/your-app, and creating workspace/root level
env files for workspace-specific settings (like the Nx Cloud token).
Pointing 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 the
envFileoption of the run-commands builder and execute your command inside of the builder
You can also define environment variables in an ad-hoc manner using support from your OS and shell.
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
set "NX_API_URL=http://localhost:3333" && nx build myapp
env:NX_API_URL = "http://localhost:3333") -and (nx build myapp)