Skip to content

Configs

Tim DeHof edited this page Oct 8, 2024 · 5 revisions

Config modules in NestJS allow you to manage configuration settings for your application in a centralized and type-safe manner. They help separate configuration concerns from business logic, making your code more maintainable and easier to test.

Module Structure

Each config module will typically consists of:

  1. An Interface file *.interface.ts
  2. A module file *.module.ts
  3. A schema file *.schema.ts for validation
  4. A service file *.service.ts for some modules

List of modules

  1. OAuth
  2. app
  3. auth
  4. database
  5. mail

How to use

  1. update your local .env file with the secrets
  2. If needed, Create a new config module:
  • Define the interface in <moduleName>Config.interface.ts
  • Create the module in <moduleName>Config.module.ts
  • Define the schema for validation in <moduleName>Config.schema.ts
  • If needed, create a service in <moduleName>Config.service.ts
  1. Import the config module into the main app.module.ts
import { Module } from '@nestjs/common';
import { AppConfigModule } from './config/app/appConfig.module';
import { AuthConfigModule } from './config/auth/authConfig.module';
// Import other config modules as needed

@Module({
  imports: [
    AppConfigModule,
    AuthConfigModule,
    // Add other config modules
  ],
  // ...
})
export class AppModule {}
  1. Use the config in the desired services:
import { Injectable } from '@nestjs/common';
import { AppConfigService } from './config/app/appConfig.service';

@Injectable()
export class YourService {
  constructor(private appConfigService: AppConfigService) {}

  someMethod() {
    const appConfig = this.appConfigService.getConfig();
    // Use the config...
  }
}

Steps to add new Oauth providers

  1. add oauth providers secrets to the .env
  2. goto src\config\Oauth folder
  3. add the oauth secrets types to the "OAuthConfig" interface in oauthConfig.interface.ts
  4. add the oauth secrets to the provider under the useFactory in oauthConfig.module.ts
  5. add the oauth secrets to the schema in oauthConfig.schema.ts

Now the env variables should type-safe and be used in the project

Additional Resources

Clone this wiki locally