Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nestjs ConfigModule.forRoot() asynchronuous

I want to load config in Nestjs from a configuration server with a REST API to allow for centralized application configuration. However there is no async version of the ConfigModule.forRoot() function so the configuration returns as undefined.

Is there any way around this ?

like image 594
Stefaan Vandevelde Avatar asked Jul 28 '26 12:07

Stefaan Vandevelde


2 Answers

Solved by creating a factory function that returns a Nest ConfigService object

// config-factory.ts
import { ConfigService } from '@nestjs/config'
import axios from 'axios'

export async function getConfigService() {
  const host = ...
  const port = ...
  const configUrl = `http://${host}:${port}/config`
  const postData = ...
  const response = await axios.post<Record<string, any> | undefined>(configUrl, postData)

  return new ConfigService(response.data)
}

@Global()
@Module({
  controllers: [],
  providers: [
    {
      provide: ConfigService,
      useFactory: getConfigService,
    },
  ],
  exports: [ConfigService],
})
export class AppModule {}
like image 57
Stefaan Vandevelde Avatar answered Jul 31 '26 03:07

Stefaan Vandevelde


According to the docs, you can inject a custom configuration file via the load parameter. Ordinarily, you would pass a synchronous factory function that returns a pre-generated object with the Record<string, any> format, but you can also pass an async factory function here, and your config will be loaded from the server before the application bootstrap without the need to inject the ConfigService as a Custom Provider (if you do that, the ConfigModule is not properly being registered in the App, you can't access it in the main.ts, and you can't use the ConfigModule options).

Example:

shared.module.ts

import { Module } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { load } from './loadConfig';

@Module({
  imports: [
    ConfigModule.forRoot({
      isGlobal: true,
      load: [async () => load({})],
    }),
  ],
  providers: [],
  exports: [],
})
export class SharedModule {}

loadConfig.ts

import { SSM } from 'aws-sdk';

export const load = async (options: any): Promise<any> => {
  const test = new SSM({ region: 'eu-north-1' });

  const parameters = await test
    .getParametersByPath({
      Path: '/path/to/ssm/route/',
      Recursive: true,
    })
    .promise();

  return parameters
};
like image 30
macca Avatar answered Jul 31 '26 01:07

macca



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!