npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@nestlib/config

v4.36.2

Published

Nestlib – Nest config – helpers for config in NestJS projects

Readme

⚙️ @nestlib/config – Configuration Module for NestJS

LSK.js NPM version NPM downloads Package size Package size Ask us in Telegram

⚙️ Environment-based: Automatic .env file detection and hierarchical resolution
🔑 Type-safe: Full TypeScript support with strict typing
🏷️ Namespaces: Multiple configuration instances with namespace support
🔄 Dynamic: Custom loaders and async module registration
📦 Multiple formats: .env, .js, .ts, .json configuration files
💉 DI Support: Dependency injection with custom decorators

🚀 Quick Start

# pnpm
pnpm add @nestlib/config

# yarn
yarn add @nestlib/config

# npm
npm i @nestlib/config
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestlib/config';

@Module({
  imports: [
    ConfigModule.forRootAsync(), // will automatically read the .env & .env.js & .env.ts files
  ],
})
export class AppModule {}

The module will automatically search for .env files in the current directory and parent directories (.env, ../.env, ../../.env).

✨ Features

  • ⚙️ Powerful configuration management for NestJS applications
  • 🌍 Environment-based configuration with automatic .env file detection
  • 📦 Built on top of @nestjs/config with extended functionality
  • 🔑 Type-safe configuration access with TypeScript support
  • 🏷️ Namespace support for multiple configuration instances
  • 🎯 Selective configuration loading with field picking
  • 🔄 Dynamic configuration with custom loaders
  • 📝 Integration with @lsk4/config for advanced config loading
  • 🌲 Hierarchical .env file resolution (searches up directory tree)
  • 💉 Dependency injection support with custom decorators
  • 🔀 Async module registration with forRootAsync for dynamic options
  • 📄 Multiple file formats: .env, .js, .ts, .json configuration files

📖 Usage

Using ConfigService

Inject and Access Configuration

import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestlib/config';

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

  getApiUrl(): string {
    return this.configService.get('API_URL');
  }

  getDatabaseConfig() {
    return {
      host: this.configService.get('DB_HOST'),
      port: this.configService.get('DB_PORT'),
      name: this.configService.get('DB_NAME'),
    };
  }
}

Using InjectConfig Decorator

import { Injectable } from '@nestjs/common';
import { InjectConfig } from '@nestlib/config';
import { ConfigService } from '@nestlib/config';

@Injectable()
export class MyService {
  constructor(
    @InjectConfig() private configService: ConfigService,
  ) {}

  getConfig() {
    return this.configService.get('SOME_VALUE');
  }
}

Environment Variables

Create a .env file in your project root:

# Application
APP_NAME=MyApp
APP_PORT=3000
NODE_ENV=development

# Database
DB_HOST=localhost
DB_PORT=5432
DB_NAME=myapp
DB_USER=postgres
DB_PASSWORD=secret

# API
API_URL=https://api.example.com
API_KEY=your-api-key

Namespaced Configuration

Use namespaces to organize multiple configuration instances:

import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestlib/config';

@Module({
  imports: [
    // Default namespace
    ConfigModule.forRoot(),
    
    // Custom namespace for database
    ConfigModule.forRoot({
      ns: 'database',
      key: 'database',
    }),
    
    // Custom namespace for redis
    ConfigModule.forRoot({
      ns: 'redis',
      key: 'redis',
    }),
  ],
})
export class AppModule {}

Inject namespaced configuration:

import { Injectable } from '@nestjs/common';
import { InjectConfig } from '@nestlib/config';
import { ConfigService } from '@nestlib/config';

@Injectable()
export class DatabaseService {
  constructor(
    @InjectConfig('database') private dbConfig: ConfigService,
  ) {}

  getConnectionString() {
    return this.dbConfig.get('connectionString');
  }
}

Dynamic Module Registration

Using getConfig Helper

The getConfig helper provides a convenient way to inject configuration into other modules:

import { Module } from '@nestjs/common';
import { getConfig } from '@nestlib/config';

@Module({
  imports: [
    SomeModule.forRootAsync(getConfig('database')),
  ],
})
export class AppModule {}

Picking Specific Fields

import { Module } from '@nestjs/common';
import { getConfig } from '@nestlib/config';

@Module({
  imports: [
    // Pick specific fields
    DatabaseModule.forRootAsync(
      getConfig('database', ['host', 'port', 'username', 'password'])
    ),
    
    // Pick all fields
    RedisModule.forRootAsync(
      getConfig('redis')
    ),
  ],
})
export class AppModule {}

Using Custom Transform Function

import { Module } from '@nestjs/common';
import { getConfig } from '@nestlib/config';

@Module({
  imports: [
    DatabaseModule.forRootAsync(
      getConfig('database', (config) => ({
        url: `postgresql://${config.username}:${config.password}@${config.host}:${config.port}/${config.database}`,
        ssl: config.ssl === 'true',
      }))
    ),
  ],
})
export class AppModule {}

Async Configuration with forRootAsync

Use forRootAsync when you need to load configuration options dynamically:

import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestlib/config';

@Module({
  imports: [
    ConfigModule.forRootAsync({
      useFactory: async () => ({
        name: 'env.config',
        cwd: '/path/to/config',
        throwError: true,
      }),
    }),
  ],
})
export class AppModule {}

Configuration File Types

The module supports multiple configuration file formats:

.env Files

# .env
DATABASE_HOST=localhost
DATABASE_PORT=5432
API_KEY=secret123

JavaScript/TypeScript Configuration Files

// env.config.ts
export default {
  database: {
    host: 'localhost',
    port: 5432,
    name: 'myapp',
  },
  api: {
    url: 'https://api.example.com',
    timeout: 5000,
  },
};

Load with:

ConfigModule.forRoot({
  name: 'env.config',
})

📚 API Reference

ConfigModule

ConfigModule.forRoot(options?: ConfigModuleOptions)

Initialize the configuration module synchronously.

Options:

interface ConfigModuleOptions {
  ns?: string;           // Namespace for this configuration instance
  key?: string | ((config: any) => any);  // Key to extract from loaded config
  name?: string;         // Name of the configuration file (default: '.env')
  cwd?: string;          // Current working directory (default: process.cwd())
  throwError?: boolean;  // Whether to throw error if config file not found
}

ConfigModule.forRootAsync(options?: ConfigModuleAsyncOptions)

Initialize the configuration module asynchronously.

interface ConfigModuleAsyncOptions {
  ns?: string;           // Namespace for this configuration instance
  imports?: any[];       // Modules to import
  inject?: InjectionToken[];  // Dependencies to inject into useFactory
  useFactory?: (...args: any[]) => Promise<ConfigModuleOptions> | ConfigModuleOptions;
  useClass?: Type<ConfigOptionsFactory>;
  useExisting?: Type<ConfigOptionsFactory>;
}

ConfigService

Service for accessing configuration values.

const apiUrl = configService.get('API_URL');
const dbHost = configService.get('database.host');

InjectConfig

Decorator for injecting ConfigService with optional namespace.

// Inject default configuration
constructor(@InjectConfig() private config: ConfigService) {}

// Inject namespaced configuration
constructor(@InjectConfig('database') private dbConfig: ConfigService) {}

getConfig

Helper function for dynamic module registration with configuration.

// Get entire configuration
SomeModule.forRootAsync(getConfig())

// Get nested path
DatabaseModule.forRootAsync(getConfig('database'))

// Pick specific fields
ApiModule.forRootAsync(getConfig(['API_URL', 'API_KEY']))

// Transform configuration
RedisModule.forRootAsync(
  getConfig('redis', (config) => ({
    host: config.host,
    port: parseInt(config.port),
  }))
)

🔧 Configuration

Environment File Resolution

The module automatically searches for .env files in the following order:

  1. {cwd}/.env
  2. {cwd}/../.env
  3. {cwd}/../../.env

File Type Detection

| File Pattern | Type | Parser | |--------------|------|--------| | .env | Environment | dotenv | | *.config (without .js/.ts/.json) | Environment | dotenv | | *.js | JavaScript | @lsk4/config | | *.ts | TypeScript | @lsk4/config | | *.json | JSON | @lsk4/config |

Variable Expansion

The module supports variable expansion in .env files:

BASE_URL=https://api.example.com
API_V1_URL=${BASE_URL}/v1
API_V2_URL=${BASE_URL}/v2

📝 License

MIT © Igor Suvorov

🔗 Links


@nestlib/configPowerful configuration management for NestJS ⚙️

Docs

Read full docs here.