Nest Typed Config

2.10.1 · active · verified Sun Apr 19

Nest-Typed-Config is a robust and intuitive configuration module designed for the NestJS framework, providing a type-safe approach to managing application settings. Unlike other configuration solutions like the official `@nestjs/config` or `nestjs-config`, this library eliminates the need for manual type-casting by allowing developers to define their configuration schema using TypeScript classes and decorators, similar to DTOs. It supports various loaders including environment variables, JSON, YAML, TOML, and remote endpoints, and integrates seamlessly with `class-validator` and `class-transformer` for comprehensive configuration validation and transformation. The current stable version is `2.10.1`, with active development and frequent releases to support new NestJS versions and introduce features like environment variable overrides and default values for file loaders.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart defines a type-safe configuration schema, loads it from a YAML file using `fileLoader`, registers it with `TypedConfigModule`, and injects the fully typed configuration directly into a NestJS service.

import { Allow, ValidateNested, IsString, IsNumber } from 'class-validator';
import { Type } from 'class-transformer';
import { Module, Injectable } from '@nestjs/common';
import { TypedConfigModule, fileLoader } from 'nest-typed-config';

// config.ts
export class TableConfig {
  @IsString()
  public readonly name!: string;
}

export class DatabaseConfig {
  @Type(() => TableConfig)
  @ValidateNested()
  public readonly table!: TableConfig;
}

export class RootConfig {
  @Type(() => DatabaseConfig)
  @ValidateNested()
  public readonly database!: DatabaseConfig;

  @IsString()
  public readonly appHost!: string;

  @IsNumber()
  public readonly appPort!: number;
}

// app.module.ts (assuming a config.yaml or .env.yaml exists in the root)
// Example config.yaml:
// database:
//   table:
//     name: myapp_main
// appHost: localhost
// appPort: 3000

@Module({
  imports: [
    TypedConfigModule.forRoot({
      schema: RootConfig,
      load: fileLoader({
        yaml: true,
        absolutePath: process.cwd(),
        ignoreEnvFile: false,
      }),
      isDevelopment: process.env.NODE_ENV !== 'production',
      validate: true,
    }),
  ],
})
export class AppModule {}

// app.service.ts
@Injectable()
export class AppService {
  constructor(private readonly config: RootConfig) {}

  getAppInfo(): string {
    return `Application running at http://${this.config.appHost}:${this.config.appPort} with table: ${this.config.database.table.name}`;
  }
}

view raw JSON →