Define environment variables with .env files in Nx
This is part of a multi-post series detailing how to consume environment variables in an Angular application, replacing the traditional environment.ts
files. The other posts can be found here:
If you want to test your Node app locally, you might need to set different environment variables based on which configuration you’re trying to test. Sure, you can do this using just the CLI, but Nx has an extensive support for .env files, which will aid you greatly in simplifying running your application locally.
Nx allows us to create multiple .env
files, which get read in depending on the launched configuration. The naming itself is quite simple: .env.<command_name>.<configuration_name>
. command_name
is the actual command executed by Nx. So for example nx serve
means our .env
file has to have the name .env.serve.development
assuming the default configuration is development
.
If we’ve got two different environments we want to use to serve our application, we can just create two different .env
files and the configurations inside project.json
. So, if we got the environments/configurations qa
and development
, we simply add the files: .env.serve.development
and .env.serve.qa
as well as the configurations in project.json
.
However, the order is important. A file in a specific app folder called .env.<command_name>.<configuration_name>
will always override a simple .env file at the repository root. In which order they get read in is described here.
For this example I’ll assume you created the app from my last post. We will only use one environment called development
with the environment variables ANGULAR_ENV
, API_URL
, and BACKGROUND_COLOR
. The configuration for development
is created by default.
Just add a .env.serve.development
file in runtime-host (not runtime-host/src
) with the following content:
# .env.serve.development
ANGULAR_ENVIRONMENT=DEVELOPMENT
API_URL=https://random.dog
BACKGROUND_COLOR=lightblue
random.dog
is a free API, which returns an URL with a random picture, gif or video of a dog. You can of course choose whichever API you want. In this case it’s just a nice visual thing (as is BACKGROUND_COLOR
).
The .env
files will not be available, nor read in, in the cloud hosted application. There we actually read out the actual environment variables. In Azure those would be the ones set in your App Configuration.