Load configuration by environment variable in NestJS application

In nestJS application, you can load the config variable with a corresponding environment variable by you can following these steps:
1. install nestjs-config package from the nestjs-config:

yarn add nestjs-config

2. create folder structure with environments folder and config folder

Environment file with structure .env[environment] (for example development, production…), you can add another environment, such as: qc, staging… (.env.qc or .env.staging) and edit package.json file following:

"scripts": {
    "build": "rimraf dist && tsc -p tsconfig.build.json",
    "format": "prettier --write \"src/**/*.ts\"",
    "start": "yarn start:dev",
    "start:dev": "tsc-watch -p tsconfig.build.json --onSuccess \"node dist/main.js\"",
    "start:qc": "cross-env NODE_ENV=qc tsc-watch -p tsconfig.build.json --onSuccess \"node dist/main.js\"",
    "start:staging": "cross-env NODE_ENV=staging tsc-watch -p tsconfig.build.json --onSuccess \"node dist/main.js\"",
    "start:debug": "tsc-watch -p tsconfig.build.json --onSuccess \"node --inspect-brk dist/main.js\"",
    "start:prod": "cross-env NODE_ENV=production node dist/main.js",
    "lint": "tslint -p tsconfig.json -c tslint.json",
    "test": "jest",
    "test:watch": "jest --watch",
    "test:cov": "jest --coverage",
    "test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
    "test:e2e": "jest --config ./test/jest-e2e.json"
  },

3. In app.module.ts file, you can load the config module with the code bellow

@Module({
  imports: [
    ConfigModule.load(resolve(__dirname, 'config', '**/!(*.d).{ts,js}'), {
      path: resolve(process.cwd(), 'environments', `.env.${ENV}`)
    }),
  ],
  providers: [
    {
      provide: APP_FILTER,
      useClass: HttpErrorFilter
    },
    {
      provide: APP_INTERCEPTOR,
      useClass: LoggingInterceptor
    }
  ]
})
export class AppModule { }

With the configuration above, then you can get config from nestJS application anywhere you want by injecting ConfigService service, for example: get pageSize config from the environment with ConfigService

The ConfigService is injected through the class constructor or you can use property-based injection

import { Inject } from '@nestjs/common';
import { ConfigService } from 'nestjs-config';
import { BaseListParamsDto } from '../dtos/base-list-params.dto';

export class BaseController {
  @Inject(ConfigService)
  readonly configService: ConfigService;
  pageSize = 15;

  getParamsForList<T extends BaseListParamsDto>(
    queries: T
  ) {
    if (this.configService.get('app.pageSize')) {
      this.pageSize = this.configService.get('app.pageSize');
    }
    const newQueries = { ...queries };
    if (!newQueries.currentPage) {
      newQueries.currentPage = 1;
    }
    if (!newQueries.pageSize) {
      newQueries.pageSize = this.pageSize;
    }
    return newQueries;
  }
}

You can click the link below to get more information from the nestjs-config package
nestjs-config

Rate this post

You May Also Like

About the Author: truongluu

Leave a Reply

Your email address will not be published. Required fields are marked *