How to get Nestjs configService instance in main.ts before instantiating app

Viewed 1445

My app instance depends on configuration : serviceName in that case

const serviceName = 'authentication-service'
const servicePrefix = `api/${serviceName}`;
const swaggerPrefix = 'swagger';
...
const app = await NestFactory.create<NestFastifyApplication>(
    AppModule,
    new FastifyAdapter({
      requestIdLogLabel: serviceName,
      logger: true,
      ...
    }),
    {
      // logger: ['log']
      logger: process.env.DEV === '1' ? ['log', 'debug', 'error', 'verbose', 'warn'] : ['error', 'warn'],
    });

NestJs documentation uses app instance to get the configService singleton :

const configService = app.get(ConfigService);
const port = configService.get('PORT');

Is there any way to get the configService instance before instantiating my app?

4 Answers

Nope. You could call dotenv's config() method yourself and populate process.env if you really need to, but that's about it. Technically, if you really wannted you could create a NestFactory.createApplicationContext() call and get the ConfigService from there, close the context and start up the application with the standard NestFactory.create, but that will end up doing the DI resolution twice, which would be a pretty slow startup

I had a similar need (for the Mikro-ORM configuration file). What I did is to create a new instance of ConfigService:

import {ConfigService} from '@nestjs/config'
const configService = new ConfigService();

Then I could use configService to get the port number:

configService.get<number>('PSQL_PORT', 5432)

What you need to do is to create a dummy app instance before the actual app.

  const configApp = await NestFactory.create(AppModule);
  let configService = configApp.get(ConfigService);

  const app = await NestFactory.create<NestFastifyApplication>(
    AppModule,
    new FastifyAdapter({
      requestIdLogLabel: serviceName,
      logger: true,
      ...
    }),
    {
      // logger: ['log']
      logger: process.env.DEV === '1' ? ['log', 'debug', 'error', 'verbose', 'warn'] : ['error', 'warn'],
    });
    //...

I am using custom configuration files as defined in https://docs.nestjs.com/techniques/configuration#custom-configuration-files

and with that I can use just use the following to get access to the config already in a js object.

async function bootstrap() {
  const conf = configuration();
  ...

I initiall tried the solution from tukusejssirs which also worked but it would not map the env entries to js object yet so I came up with this one.

Comments appreciated as it feels a bit weird...

Related