0
0
NestJSframework~5 mins

Custom configuration files in NestJS

Choose your learning style9 modes available
Introduction

Custom configuration files help you organize settings for your NestJS app. They keep your code clean and make it easy to change settings without touching the main code.

You want to separate database settings from your main code.
You need different settings for development and production.
You want to keep API keys or secrets outside your main code.
You want to easily update app settings without redeploying code.
Syntax
NestJS
import { registerAs } from '@nestjs/config';

export default registerAs('customConfig', () => ({
  key: 'value',
  anotherKey: 123
}));

Use registerAs to create a named configuration file.

The function returns an object with your settings.

Examples
This example creates a database config with connection details.
NestJS
import { registerAs } from '@nestjs/config';

export default registerAs('database', () => ({
  host: 'localhost',
  port: 5432,
  username: 'user',
  password: 'pass'
}));
This example uses environment variables with a fallback value.
NestJS
import { registerAs } from '@nestjs/config';

export default registerAs('api', () => ({
  key: process.env.API_KEY || 'defaultKey',
  timeout: 5000
}));
Sample Program

This module loads the custom config file and prints the value of key from it.

NestJS
import { Module } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import customConfig from './custom.config';

@Module({
  imports: [
    ConfigModule.forRoot({
      load: [customConfig]
    })
  ]
})
export class AppModule {
  constructor(private configService: ConfigService) {
    const value = this.configService.get('customConfig.key');
    console.log('Custom config key:', value);
  }
}
OutputSuccess
Important Notes

Always keep sensitive data like passwords in environment variables, not in config files.

You can create multiple custom config files and load them all in ConfigModule.forRoot.

Access config values using dot notation with ConfigService.get().

Summary

Custom config files keep your app settings organized and separate from code.

Use registerAs to create named config files that return settings objects.

Load custom configs with ConfigModule.forRoot({ load: [...] }) and access them via ConfigService.