Using environment variables in Angular applications
For Angular applications using ESBuild
Setting the define
option of the application
executor
Required Angular versionSupport for the define
option requires Angular 17.2.0 or later.
In Angular applications using the @nx/angular:application
or @angular-devkit/build-angular:application
executors, you can set the define
option in the build
target to define variables that will be available in your application code at build time:
1{
2 ...
3 "targets": {
4 "build": {
5 "executor": "@nx/angular:application",
6 "options": {
7 ...
8 "define": {
9 "MY_API_URL": "http://localhost:3333"
10 }
11 }
12 },
13 ...
14 }
15}
16
When you use one of the @nx/angular
executors for building your applications, make sure to also change the serve
executor to @nx/angular:dev-server
to ensure the extra features provided by Nx are also available when serving the application.
Next, make sure to inform TypeScript of the defined variables to prevent type-checking errors during the build. We can achieve this in a number of ways. For example you could create or update a type definition file included in the TypeScript build process (e.g. src/types.d.ts
) with declare
statements for the defined variables:
1declare const MY_API_URL: string;
2
The above would allow you to use the MY_API_URL
variable in your application code as in the following example:
1import { Injectable } from '@angular/core';
2
3({ providedIn: 'root' })
4export class ApiService {
5 constructor() {
6 console.log('API URL:', MY_API_URL);
7 }
8}
9
You can also define the variables in a way that allows you to consume them as you would do in Node.js applications:
1{
2 ...
3 "targets": {
4 "build": {
5 "executor": "@nx/angular:application",
6 "options": {
7 ...
8 "define": {
9 "process.env.MY_API_URL": "http://localhost:3333"
10 }
11 }
12 },
13 ...
14 }
15}
16
Like the previous example, you must configure TypeScript to recognize the process.env
object. You can do this by defining the process.env
object in a type definition file:
1declare const process: {
2 env: {
3 API_URL: string;
4 };
5};
6
You could also add the Node.js types to your tsconfig.json
file, but this would add many types that you don't need in a browser environment. This can be misleading since you'll see some types are available, but the runtime functionality won't be. It's better to define only the types you need in a type definition file.
And then use the variable in your application code:
1import { Injectable } from '@angular/core';
2
3({ providedIn: 'root' })
4export class ApiService {
5 constructor() {
6 console.log('API URL:', process.env.MY_API_URL);
7 }
8}
9
Using a custom ESBuild plugin
Required Angular versionSupport for custom ESBuild plugins requires Angular 17.0.0 or later.
The previous method is useful to statically define variables in the project configuration that will be available at build time. However, if you need to dynamically collect and define the environment variables available at build time, you can create a custom ESBuild plugin.
You can provide a custom ESBuild plugin to the @nx/angular:application
or @nx/angular:browser-esbuild
executors:
1{
2 ...
3 "targets": {
4 "build": {
5 "executor": "@nx/angular:application",
6 "options": {
7 ...
8 "plugins": ["apps/my-app/plugins/env-var-plugin.js"]
9 }
10 },
11 ...
12 }
13}
14
Next, create the custom ESBuild plugin:
1const myOrgEnvRegex = /^MY_ORG_/i;
2
3const envVarPlugin = {
4 name: 'env-var-plugin',
5 setup(build) {
6 const options = build.initialOptions;
7
8 const envVars = {};
9 for (const key in process.env) {
10 if (myOrgEnvRegex.test(key)) {
11 envVars[key] = process.env[key];
12 }
13 }
14
15 options.define['process.env'] = JSON.stringify(envVars);
16 },
17};
18
19module.exports = envVarPlugin;
20
The plugin collects all environment variables that start with MY_ORG_
and defines them in the process.env
object. You can adjust the plugin to your needs (e.g., use a different regular expression, use a whitelist, add all environment variables, etc.).
As shown in the previous section, add the defined variables to a type definition file to ensure TypeScript recognizes them.
Now, you can define variables in an .env
file, such as:
1MY_ORG_API_URL=http://localhost:3333
2
Alternatively, you can also set environment variables when running a terminal command.
Finally, you can use the environment variables in your application code:
1import { Injectable } from '@angular/core';
2
3({ providedIn: 'root' })
4export class ApiService {
5 constructor() {
6 console.log('API URL:', process.env.MY_ORG_API_URL);
7 }
8}
9
For Angular applications using Webpack
Angular executors for Webpack (e.g. @nx/angular:webpack-browser
and @angular-devkit/build-angular:browser
) don't have built-in support for using environment variables when building applications.
To add support for environment variables we need to use the webpack DefinePlugin
in our own custom webpack configuration. We'll see how to do so in the following sections.
A note on NODE_ENV
The webpack-based Angular executors (e.g. @nx/angular:webpack-browser
and @angular-devkit/build-angular:browser
) set the webpack's mode
configuration option based on the values for the following in the builder options:
optimization
optimization.scripts
optimization.styles
optimization.styles.minify
If any of the above is set to true
, webpack's mode
is set to production
. Otherwise, it's set to development
.
By default, webpack automatically sets the NODE_ENV
variable to the value of the mode
configuration option. Therefore, Angular applications code have access to that environment variable at build time, but we can't change the NODE_ENV
variable value directly as we would do with other environment variables because Angular always set the mode
configuration option based on the above.
To change the NODE_ENV
variable we can do one of the following:
- Turn on the builder optimizations to set it to
production
- Turn off the builder optimizations to set it to
development
- Use a custom webpack configuration to override the webpack
mode
set by Angular executors
The first two options is a matter of changing your build target configuration or passing the specific flag in the command line. We'll see how to do the last in the following section.
Use a custom webpack configuration to support environment variables
Update the build
and serve
targets to use the @nx/angular
relevant executors and provide a custom Webpack configuration:
1{
2 ...
3 "targets": {
4 "build": {
5 "executor": "@nx/angular:webpack-browser",
6 "options": {
7 ...
8 "customWebpackConfig": {
9 "path": "apps/my-app/webpack.config.js"
10 }
11 }
12 },
13 "serve": {
14 "executor": "@nx/angular:dev-server"
15 ...
16 },
17 ...
18 }
19}
20
Then, we can use DefinePlugin
in our custom Webpack configuration:
1const webpack = require('webpack');
2
3const myOrgEnvRegex = /^MY_ORG_/i;
4
5function getClientEnvironment() {
6 const envVars = {};
7 for (const key in process.env) {
8 if (myOrgEnvRegex.test(key)) {
9 envVars[key] = process.env[key];
10 }
11 }
12
13 return {
14 'process.env': JSON.stringify(envVars),
15 };
16}
17
18module.exports = (config, options, context) => {
19 // Overwrite the mode set by Angular if the NODE_ENV is set
20 config.mode = process.env.NODE_ENV || config.mode;
21 config.plugins.push(new webpack.DefinePlugin(getClientEnvironment()));
22 return config;
23};
24
In our custom Webpack configuration we collect all environment variables that start with MY_ORG_
, define the process.env
object with them, and provide it to the DefinePlugin
. You can adjust the configuration to your needs (e.g., use a different regular expression, use a whitelist, add all environment variables, etc.).
Next, make sure to inform TypeScript of the defined variables to prevent type-checking errors during the build. We can achieve this in a number of ways. For example you could create or update a type definition file included in the TypeScript build process (e.g. src/types.d.ts
) with declare
statements for the defined variables:
1declare const process: {
2 env: {
3 MY_ORG_API_URL: string;
4 };
5};
6
Now, we can define variables in our .env
file, such as:
1MY_ORG_API_URL=http://localhost:3333
2
Alternatively, you can also set environment variables when running a terminal command.
Finally, we can use environment variables in our code:
1import { Injectable } from '@angular/core';
2
3({ providedIn: 'root' })
4export class ApiService {
5 constructor() {
6 console.log('API URL:', process.env.MY_ORG_API_URL);
7 }
8}
9
Using environment variables in index.html
While you cannot use environment variables in index.html
, one workaround is to create different index.*.html
files, such as index.prod.html
, then swap them in different environments.
For example, you can configure your build
target in project.json
as follows:
1{
2 ...
3 "targets": {
4 "build": {
5 "executor": "@angular-devkit/build-angular:browser",
6 ...
7 "configurations": {
8 "production": {
9 ...
10 "fileReplacements": [
11 {
12 "replace": "apps/my-app/src/index.html",
13 "with": "apps/my-app/src/index.prod.html"
14 }
15 ]
16 }
17 }
18 }
19 }
20}
21
You can also customize your webpack configuration, similar to using DefinePlugin
above. This approach will require post-processing the index.html
file, and is out of scope for this guide.