Loading of port number for Nest.js application from JSON module

Try https://www.npmjs.com/package/neconfig for elegant config NestJs app.

Just register NeconfigModule in your AppModule:

import { Module } from "@nestjs/common";
import { NeconfigModule } from 'neconfig';
import * as path from 'path';

@Module({
  imports: [
    NeconfigModule.register({
      readers: [
        { name: 'env', file: path.resolve(process.cwd(), '.env') },
      ],
    }),
  ],
})
export class AppModule { }

Then use it like that:

import { Logger } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { ConfigReader } from 'neconfig';
import { AppModule } from './app.module';

(async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  const config = app.get(ConfigReader);
  const port = config.getIntOrThrow('PORT');
  // const port = config.getInt('PORT', 3000);

  await app.listen(port);
  Logger.log(`Listening on http://localhost:${port}`);
})();

Workaround in 2021:

main.ts, NestJS v8.0.4

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { ConfigService } from '@nestjs/config';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  const configService: ConfigService = app.get<ConfigService>(ConfigService);
  const port = configService.get('APP_PORT');
  await app.listen(port);
}
bootstrap();

Profit!


Yes. Use this - https://docs.nestjs.com/techniques/configuration part of NestJS docs to create ConfigService. You can replace dotenv with json if you want. Then:

import {NestFactory} from '@nestjs/core';
import {ConfigService} from 'src/config/config.service';
import {AppModule} from './app.module';

let bootstrap = async () => {
    const app = await NestFactory.create(AppModule);
    const configService: ConfigService = app.get(ConfigService);
    await app.listen(configService.getPort);
};

bootstrap();

Now you can inject ConfigService in most part of your code + whle loading you can validate it using Joi. Hope this helps.