Using Environment Variables in Nx 19 with Angular

Ekrem Koçak
3 min readSep 8, 2024

--

In the world of development, making projects modular and manageable is a common goal. Nx and Angular are quite popular in this context. In this article, I’ll walk you through how to manage environment variables using Nx 19 and Angular 18.

1. Creating an Nx Workspace

The first step is to create an Nx workspace using the npx create-nx-workspace command. This command launches an interactive setup wizard that helps you configure your workspace. You can start by selecting Angular when prompted.

npx create-nx-workspace my-workspace

2. Creating Environment Files

After setting up your project, you need to create the src/environments folder and add the necessary environment files. These files store the different configurations for your application in various environments (development, production, etc.).

environment.ts

import { EnvironmentModel } from './environment.model';

export const environment: EnvironmentModel = {
apiUrl: 'local',
};

environment.prod.ts

import { EnvironmentModel } from './environment.model';

export const environment: EnvironmentModel = {
apiUrl: 'prod',
};

3. Creating an Injection Token

To access the environment variables throughout your application, we create an Injection Token. This allows you to use Angular’s dependency injection system to provide and access the configuration wherever it’s needed.

import { InjectionToken } from '@angular/core';
import { EnvironmentModel } from './environment.model';

export const APP_CONFIG = new InjectionToken<EnvironmentModel>(
'Application config'
);

4. Providing the Injection Token in App Config

Next, we provide the Injection Token in the app.config.ts file, which contains the global configuration for your application.

import { ApplicationConfig, provideZoneChangeDetection } from '@angular/core';
import { provideRouter } from '@angular/router';
import { appRoutes } from './app.routes';
import { environment } from 'src/environments/environment';
import { APP_CONFIG } from 'src/environments/app-config.token';

export const appConfig: ApplicationConfig = {
providers: [
provideRouter(appRoutes),
{ provide: APP_CONFIG, useValue: environment },
],
};

5. Applying File Replacement for Different Environments

To use different environment files for different configurations, you need to set up fileReplacements in the project.json file or Nx configuration. This feature allows you to specify which file should replace another for a given configuration (e.g., production).

{
"name": "my-project",
"targets": {
"build": {
"executor": "@angular-devkit/build-angular:application",
"options": {
"outputPath": "dist/my-project",
},
"configurations": {
"production": {
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.prod.ts"
}
]
}
}
}
}
}

6. Accessing the Environment Variable in the Application

Let’s see how to access the environment variable within your application. In this example, we access the environment variable using the InjectionToken within the AppComponent.

import { Component, inject } from '@angular/core';
import { RouterModule } from '@angular/router';
import { APP_CONFIG } from 'src/environments/app-config.token';

@Component({
standalone: true,
imports: [RouterModule],
selector: 'app-root',
templateUrl: './app.component.html',
})
export class AppComponent {
private readonly appConfig = inject(APP_CONFIG);

/** consturctor injection */
// constructor(@Inject(APP_CONFIG) appConfig: EnvironmentModel) {}
constructor() {
console.log(this.appConfig.apiUrl); // Outputs 'local' in development and 'prod' in production
}
}

7. Running the Application

To run the project, you can use the nx serve command. By default, this command starts the project in the development environment, and you should see "local" in the console.log output.

nx serve

To run the application in the production environment, add the --c=production flag.

nx serve --c=production

This time, you should see “prod” in the console output.

Conclusion

Managing environment variables with Nx and Angular makes your projects modular and easier to manage. In this guide, I walked you through how to set up and use environment variables step by step. This setup allows you to easily configure your projects for different environments, making long-term maintenance much simpler.

GitHub Repository

StackBlitz

--

--

Responses (1)