When using environment variables in the ClientsModule or any other module, the common approach is to utilize the configuration service or module. In Node.js applications, environment variables are typically loaded at startup from a .env file or system environment and can be accessed via process.env. However, in a well-structured NestJS application, you might use the ConfigModule to handle environment variables.
- Install ConfigModule (if not already installed)
First, confirm that @nestjs/config is installed. If not, you can install it using the following command:
shellnpm install @nestjs/config
- Import ConfigModule
Import ConfigModule in the application's root module (typically AppModule). You can choose to load the .env file immediately and set validation rules.
typescriptimport { Module } from '@nestjs/common'; import { ConfigModule } from '@nestjs/config'; import { ClientsModule } from './clients/clients.module'; @Module({ imports: [ ConfigModule.forRoot({ isGlobal: true, // Makes ConfigService available globally // envFilePath: '.env', // Specify the path to the env file if needed // ignoreEnvFile: process.env.NODE_ENV === 'production', // Ignore .env file in production // validationSchema: Joi.object({...}), // Use Joi for validation if needed }), ClientsModule, ], // ... }) export class AppModule {}
Setting isGlobal to true makes ConfigModule and ConfigService available throughout the application, eliminating the need to import them in each module.
- Use ConfigService in ClientsModule
Now, you can inject ConfigService into ClientsModule or its services and controllers to access environment variables.
typescriptimport { Module } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; import { ClientsService } from './clients.service'; @Module({ providers: [ClientsService], // ... }) export class ClientsModule { constructor(private configService: ConfigService) {} someMethod() { // Use ConfigService to get environment variables const clientApiUrl = this.configService.get<string>('CLIENT_API_URL'); // ... } }
Within the someMethod method, clientApiUrl loads the value of the environment variable named CLIENT_API_URL. The get method provided by ConfigService also allows you to specify a generic type to determine the return value's type.
- Use Environment Variables
You can use the injected ConfigService at any location within the module to retrieve and utilize environment variables. For example, when connecting to a database or client API in a service, you may need to use the connection string from the environment variables.
typescriptexport class ClientsService { private apiEndpoint: string; constructor(private configService: ConfigService) { this.apiEndpoint = this.configService.get<string>('CLIENT_API_URL', { infer: true }); } async fetchData() { const data = await fetch(`${this.apiEndpoint}/data`); // ... } }
In this example, ClientsService reads the environment variable CLIENT_API_URL in the constructor to set the API endpoint address and uses it in the fetchData method.
The above steps demonstrate how to use environment variables in the ClientsModule of a NestJS application, ensuring that your configuration is maintainable and testable.