Skip to main content

300. Configs

Setup Configs

  1. save configuration files (environment variables), inside .env files
  2. load .env files using @nest/config library
  3. use the variables using process.env.[variable_name]
npm i --save @nestjs/config
@Module({
imports: [
ConfigModule.forRoot(),
TypeOrmModule.forRoot({
type: 'postgres',
host: process.env.DATABASE_HOST,
port: +process.env.DATABASE_PORT,
username: process.env.DATABASE_USER,
//...
}),
],
})
export class AppModule {}

Custom .env Path

ConfigModule.forRoot({
envFilePath: '.development.env',
});
  • we can configure configmodule behavior by defining different options
    • ignoreEnvFile
      • this is useful to prevent configmodule from looking .env to load environment variables…this is useful for cases such as providing environment variables using hosting ui instead of .env
ConfigModule.forRoot({
ignoreEnvFile: true
})

Using Config Service

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

constructor(private readonly configService: ConfigService){

const db_password = this.configService.get<string>('DATABASE_PASSWORD');

//CAN ALSO WORK WITH DEFAULT VALUE
const db_password = this.configService.get<string>('DATABASE_PASSWORD', 'password');
}
}

it's possible to define different configurations per section of your app, and use config module to load them flexibly

always prefer using configService.get('key') instead of using process.env.key

Cache Environment Variables

  • Configuration | NestJS - A progressive Node.js framework
  • As accessing process.env can be slow, you can set the cache property of the options object passed to ConfigModule.forRoot() to increase the performance of ConfigService#get method when it comes to variables stored in process.env.

ConfigModule.forRoot({
cache: true,
});

Config Validation

npm install --save joi
ConfigModule.forRoot({
validationSchema: Joi.object({
DATABASE_HOST: Joi.required(),
DATABASE_PORT: Joi.number().default(5432)
})
}),

Using Config in main.ts

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