Skip to content

p-fedyukovich/nestjs-config

Repository files navigation

NestJS Node Config Module

Nest Logo

Node Config

Node.js Application Configuration organizes hierarchical configurations for your app deployments.

It lets you define a set of default parameters, and extend them for different deployment environments (development, qa, staging, production, etc.).

Installation

To start using Node Config module, first install the required packages:

$ npm i --save config nestjs-node-config-module

Overview

To use the config module, add ConfigModule import:

import { ConfigModule } from "nestjs-node-config-module";

@Module({
  imports: [ConfigModule.forRoot()],
  controllers: [],
  providers: [],
})
export class AppModule {
}

Then you can inject config service:

import { ConfigService } from "nestjs-node-config-module";

@Injectable()
export class AppService {
  constructor(private configService: ConfigService) {
  }

  getFoo(): string {
    return this.configService.get('foo');
  }
}

Options

Config module accepts optional options parameter, parameters are described below:

nodeEnv Overrides the value of NODE_ENV
configDir Contains the paths to the directories containing your configuration files.
printConfigSources If true prints config source on module setup
strictMode Strict mode (read more here)
configService Class that extends default ConfigService, you can use it to have all settings in one place

ConfigService

You can extend default config service with your one, for example:

import { ConfigService } from "nestjs-node-config-module";

@Injectable()
class MyConfigService extends ConfigService {
  getFoo(): string {
    return this.get<string>('foo')
  }
}

Then you have to register it by passing class to Config Module:

import { ConfigModule } from "nestjs-node-config-module";

@Module({
  imports: [ConfigModule.forRoot({
    configService: MyConfigService
  })],
  controllers: [],
  providers: [],
})
export class AppModule {
}

And now it's accessible in nest IoC container:

import { MyConfigService } from "./my-config.service";

@Injectable()
export class AppService {
  constructor(private configService: MyConfigService) {
  }

  getFoo(): string {
    return this.configService.getFoo();
  }
}

NOTE: default ConfigService is still available and can be injected.