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

@elsikora/nestjs-crud-config

v3.0.0

Published

NestJS application configuration via database storage

Readme

📚 Table of Contents

📖 Description

NestJS CRUD Config is a powerful configuration management module that revolutionizes how NestJS applications handle configuration data. Unlike traditional environment variable approaches, this library stores configuration in a database with full CRUD operations, making it perfect for dynamic configuration management across multiple environments and services.

The module provides hierarchical organization through sections and data entries, supports optional AES-256-GCM encryption for sensitive values, and includes automatic REST API endpoints for configuration management. Built with TypeScript-first design and leveraging the NestJS CRUD Automator for automatic API generation, it features dynamic entity creation at runtime, named transaction ownership, and intelligent caching.

Whether you're managing API keys across different environments, storing feature flags, or maintaining application settings that need to change without redeployment, this module provides a robust, secure, and scalable solution for microservice architectures, multi-tenant applications, and any system requiring centralized, database-backed configuration management with real-time updates.

🚀 Features

  • 🗄️ Database-backed configuration storage - Store configuration in any TypeORM-supported database for persistence and scalability
  • 🏗️ Dynamic entity creation - Entities are created at runtime with customizable table names, field lengths, and constraints
  • 📊 Hierarchical organization - Organize configuration using sections and data entries for better structure and management
  • 🔐 AES-256-GCM encryption support - Protect sensitive configuration values with built-in encryption using industry-standard algorithms
  • 🌍 Multi-environment support - Manage configurations across development, staging, and production environments seamlessly
  • ⚡ Full CRUD operations - Complete Create, Read, Update, Delete operations with automatic REST API endpoints
  • 📚 Automatic Swagger documentation - Generated OpenAPI documentation for all configuration endpoints
  • 🎯 TypeScript-first design - Full type safety with comprehensive interfaces and type definitions
  • 🚀 NestJS CRUD Automator integration - Leverages advanced CRUD automation for controllers and services
  • 💾 Intelligent caching - Built-in caching support with configurable TTL and cache size limits
  • 🔄 Named transaction ownership - Each Automator-owned unit of work uses one exact TypeORM manager, including joined migration writes
  • 🎛️ Highly customizable - Configure table prefixes, field lengths, validation rules, and entity relationships
  • 🚦 Flexible controller configuration - Customize API paths, disable endpoints, or run in headless mode
  • 🔧 Advanced CRUD customization - Full control over routes, swagger documentation, and controller behavior
  • 📦 Modular architecture - Enable/disable features as needed for your use case
  • 🚀 Production-ready migration system - Initialize and manage configuration state during application startup

🛠 Installation

These docs describe the upcoming CrudConfig 3.0 contract. Use the 3.x-only range below. It intentionally fails until a 3.0 prerelease exists instead of resolving incompatible CrudConfig 2.x:

# npm
npm install @elsikora/nestjs-crud-config@^3.0.0-0

# yarn
yarn add @elsikora/nestjs-crud-config@^3.0.0-0

# pnpm
pnpm add @elsikora/nestjs-crud-config@^3.0.0-0

Prerequisites

Install the required peer dependencies:

npm install @elsikora/nestjs-crud-automator@^3.0.2 @nestjs/common@^11.1.24 @nestjs/core@^11.1.24 @nestjs/typeorm@^11.0.0 typeorm@^0.3.20
npm install @nestjs/passport@^11.0.5 @nestjs/platform-fastify@^11.1.24 @nestjs/[email protected] @nestjs/throttler@^6.5.0 class-transformer@^0.5.1 class-validator@^0.15.1 fastify@^5.8.5 lodash@^4.18.1

Automator 3 compatibility

The upcoming CrudConfig 3 release requires @elsikora/nestjs-crud-automator >=3.0.2-0 <4.0.0. Automator 2 is not supported.

Generated route overrides continue to use Automator generation config:

DELETE: {
 generation: {
  isEnabled: false,
 },
},

ConfigData CREATE and UPDATE use Automator nested request relation loading. The built-in section relation expects request bodies such as { "section": { "id": "section-uuid" } }.

The tested Swagger baseline is exact 11.4.2. See Migrating to 3.0 for transaction and EventEmitter changes.

Migrating to 3.0

The upcoming 3.0 release is breaking:

  • Automator 2 compatibility is removed.
  • Transaction-enabled migration execution and rollback use the named crud-config-migrations Automator owner.
  • Standalone CrudConfigService.set() uses the named crud-config-set owner.
  • Migration config operations must receive the callback EntityManager through eventManager so they join instead of opening a nested owner.
  • The ConfigData before-insert EventEmitter pipeline and @nestjs/event-emitter dependency are removed.
  • The database unique constraint remains authoritative, and Automator maps duplicate writes to 409 CONFIGDATA_DUPLICATE_KEY.

See the complete 3.0 migration guide.

Database Support

This package works with any database supported by TypeORM:

  • PostgreSQL
  • MySQL/MariaDB
  • SQLite
  • Microsoft SQL Server
  • Oracle
  • MongoDB
  • CockroachDB

💡 Usage

Basic Setup

// app.module.ts
import { Module } from "@nestjs/common";
import { TypeOrmModule } from "@nestjs/typeorm";
import { CrudConfigModule, TOKEN_CONSTANT } from "@elsikora/nestjs-crud-config";

@Module({
 imports: [
  // First register CrudConfigModule to create dynamic entities
  CrudConfigModule.register({
   environment: "development",
   shouldAutoCreateSections: true,

   // Cache configuration
   cacheOptions: {
    isEnabled: true,
    maxCacheItems: 1000,
    maxCacheTTL: 3600000, // 1 hour in milliseconds
   },

   // Encryption configuration
   encryptionOptions: {
    isEnabled: true,
    encryptionKey: process.env.CONFIG_ENCRYPTION_KEY, // 32+ character key
   },

   // Controller configuration (optional)
   controllersOptions: {
    section: {
     isEnabled: true,
     properties: {
      path: "api/config/sections",
     },
    },
    data: {
     isEnabled: true,
     properties: {
      path: "api/config/data",
     },
    },
   },

   // Entity customization
   entityOptions: {
    tablePrefix: "app_",
    configSection: {
     tableName: "config_sections",
     maxNameLength: 128,
     maxDescriptionLength: 512,
    },
    configData: {
     tableName: "config_data",
     maxValueLength: 8192,
     maxEnvironmentLength: 64,
     maxNameLength: 128,
     maxDescriptionLength: 512,
    },
   },
  }),

  // Then register TypeORM with dynamic entities using registerAsync
  TypeOrmModule.forRootAsync({
   imports: [CrudConfigModule],
   inject: [TOKEN_CONSTANT.CONFIG_SECTION_ENTITY, TOKEN_CONSTANT.CONFIG_DATA_ENTITY],
   useFactory: async (sectionEntity, dataEntity) => ({
    type: "postgres",
    host: "localhost",
    port: 5432,
    username: "postgres",
    password: "postgres",
    database: "config_db",
    entities: [
     // Your other entities
     // UserEntity, ProductEntity, etc.

     // Dynamic entities from CrudConfigModule
     sectionEntity,
     dataEntity,
    ],
    synchronize: true,
   }),
  }),
 ],
})
export class AppModule {}

Using the Configuration Service

// config.service.ts
import { Injectable } from "@nestjs/common";
import { CrudConfigService } from "@elsikora/nestjs-crud-config";

@Injectable()
export class MyConfigService {
 constructor(private readonly configService: CrudConfigService) {}

 async setupApplicationConfig() {
  // Set a configuration value
  await this.configService.set({
   section: "api-settings",
   name: "API_KEY",
   value: "my-secret-api-key",
   description: "Production API key",
   environment: "production",
  });

  // Retrieve configuration by section and name
  const apiConfig = await this.configService.get({
   section: "api-settings",
   name: "API_KEY",
   environment: "production",
   shouldLoadSectionInfo: true,
   useCache: true,
  });

  console.log("API Configuration:", apiConfig);
  // apiConfig.value will be automatically decrypted if it was encrypted

  return apiConfig;
 }

 async getConfigurationList() {
  // Get all configurations in a section
  const configs = await this.configService.getList({
   section: "api-settings",
   environment: "production",
   useCache: true,
  });

  return configs;
 }

 async deleteConfiguration() {
  // Delete a configuration
  await this.configService.delete({
   section: "api-settings",
   name: "API_KEY",
   environment: "production",
  });
 }
}

Async Module Registration

When using registerAsync(), static options like controllers and entity configuration must be provided via the staticOptions property, as NestJS does not support async controller registration:

// app.module.ts
import { Module } from "@nestjs/common";
import { ConfigModule, ConfigService } from "@nestjs/config";
import { CrudConfigModule } from "@elsikora/nestjs-crud-config";

@Module({
 imports: [
  ConfigModule.forRoot(),
  CrudConfigModule.registerAsync({
   imports: [ConfigModule],
   inject: [ConfigService],
   // Dynamic options - resolved asynchronously
   useFactory: async (configService: ConfigService) => ({
    environment: configService.get("NODE_ENV", "development"),
    encryptionOptions: {
     isEnabled: true,
     encryptionKey: configService.get("ENCRYPTION_KEY"),
    },
    cacheOptions: {
     isEnabled: true,
     maxCacheItems: 1000,
     maxCacheTTL: 3600000,
    },
   }),
   // Static options - must be known at module registration time
   staticOptions: {
    controllersOptions: {
     section: {
      isEnabled: true,
      properties: {
       path: "api/config/sections",
      },
     },
     data: {
      isEnabled: true,
      properties: {
       path: "api/config/data",
      },
     },
    },
    entityOptions: {
     tablePrefix: "app_",
     configSection: {
      tableName: "config_sections",
      maxNameLength: 128,
     },
     configData: {
      tableName: "config_data",
      maxValueLength: 8192,
     },
    },
    migrationEntityOptions: {
     tableName: "config_migrations",
    },
   },
  }),
 ],
})
export class AppModule {}

Important: The staticOptions property contains configuration that must be known at module compilation time:

  • controllersOptions - REST API controller configuration
  • entityOptions - Database entity customization (table names, field lengths)
  • migrationEntityOptions - Migration tracking table configuration

🚀 Migration System

The NestJS CRUD Config module includes a powerful production-ready migration system that allows you to initialize and manage configuration state during application startup. This system ensures your application always has the required configuration data across different environments and deployments.

Key Features

  • 🔄 Automatic execution on startup - Migrations run automatically when the application bootstraps
  • 💾 Named transaction support - Transaction-enabled migrations run inside one named Automator owner
  • 🌍 Environment-specific configurations - Create different configurations for different environments
  • 📊 Migration tracking - Complete audit trail with timestamps and execution status
  • 🔙 Rollback support - Define rollback procedures for each migration
  • ⚡ Stuck migration cleanup - Automatic timeout and cleanup of crashed migrations
  • 🎯 Type-safe status tracking - Uses EConfigMigrationStatus enum for reliable status management
  • 🛡️ Race condition protection - Thread-safe execution preventing concurrent conflicts

Migration Status Enum

The migration system uses the EConfigMigrationStatus enum to track migration states:

import { EConfigMigrationStatus } from "@elsikora/nestjs-crud-config";

// Available statuses:
EConfigMigrationStatus.PENDING; // Migration is pending execution
EConfigMigrationStatus.RUNNING; // Migration is currently running
EConfigMigrationStatus.COMPLETED; // Migration completed successfully
EConfigMigrationStatus.FAILED; // Migration failed with error
EConfigMigrationStatus.STUCK; // Migration is stuck (timeout)

Basic Migration Configuration

Configure migrations in your module registration:

import { CrudConfigModule } from "@elsikora/nestjs-crud-config";
import { initialAppConfigMigration } from "./migrations/001-initial-app-config.migration";

@Module({
 imports: [
  CrudConfigModule.register({
   environment: process.env.NODE_ENV || "development",

   // Migration configuration
   migrationOptions: {
    isEnabled: true,
    shouldRunOnStartup: true,
    useTransaction: true,
    stuckMigrationTimeoutMinutes: 30,
    tableName: "config_migrations", // Optional: custom table name

    migrations: [
     initialAppConfigMigration,
     // Add more migrations here
    ],
   },

   // Other configuration options...
  }),
 ],
})
export class AppModule {}

With useTransaction: true (the default), execution owns one crud-config-migrations transaction and passes its exact EntityManager to each migration callback. Pass that manager as eventManager to every config operation in the migration. Omitting it from set() would attempt to open the separate crud-config-set owner, and Automator rejects nested owners.

With useTransaction: false, there is no migration-wide owner and callbacks receive undefined. A standalone set() still owns its own atomic crud-config-set transaction, so several config writes are not one all-or-nothing unit. Rollback execution always uses the named migration owner.

Creating Migration Files

Create a migration file with the required structure:

// migrations/001-initial-app-config.migration.ts
import type { IConfigMigrationDefinition } from "@elsikora/nestjs-crud-config";
import type { CrudConfigService } from "@elsikora/nestjs-crud-config";
import type { EntityManager } from "typeorm";

export const initialAppConfigMigration: IConfigMigrationDefinition = {
 name: "001_initial_app_config",
 description: "Initialize basic application configuration",

 async up(configService: CrudConfigService, entityManager?: EntityManager): Promise<void> {
  // Create application settings
  await configService.set({
   section: "app-settings",
   name: "APP_NAME",
   value: "My Application",
   description: "Application name",
   environment: "default",
   eventManager: entityManager,
  });

  await configService.set({
   section: "app-settings",
   name: "APP_VERSION",
   value: "1.0.0",
   description: "Application version",
   environment: "default",
   eventManager: entityManager,
  });

  // Create API settings
  await configService.set({
   section: "api-settings",
   name: "API_RATE_LIMIT",
   value: "100",
   description: "API rate limit per minute",
   environment: "default",
   eventManager: entityManager,
  });
 },

 async down(configService: CrudConfigService, entityManager?: EntityManager): Promise<void> {
  // Rollback: remove configurations created by this migration
  const configurationsToRemove = [
   { name: "APP_NAME", section: "app-settings" },
   { name: "APP_VERSION", section: "app-settings" },
   { name: "API_RATE_LIMIT", section: "api-settings" },
  ];

  for (const config of configurationsToRemove) {
   try {
    await configService.delete({
     section: config.section,
     name: config.name,
     environment: "default",
     eventManager: entityManager,
    });
   } catch (error) {
    // Expected if config was never created
    console.warn(`Failed to delete config ${config.section}:${config.name} during rollback`);
   }
  }
 },
};

Environment-Specific Migrations

Create migrations that work with different environments:

// migrations/002-environment-specific-config.migration.ts
export const environmentSpecificConfigMigration: IConfigMigrationDefinition = {
 name: "002_environment_specific_config",
 description: "Environment-specific configuration settings",

 async up(configService: CrudConfigService, entityManager?: EntityManager): Promise<void> {
  const environments = ["development", "staging", "production"];

  for (const env of environments) {
   // Environment-specific debug settings
   await configService.set({
    section: "app-settings",
    name: "DEBUG_MODE",
    value: env === "development" ? "true" : "false",
    description: "Enable debug mode",
    environment: env,
    eventManager: entityManager,
   });

   // Environment-specific API limits
   const rateLimits = {
    development: "1000",
    staging: "500",
    production: "100",
   };

   await configService.set({
    section: "api-settings",
    name: "API_RATE_LIMIT",
    value: rateLimits[env],
    description: "API rate limit per minute",
    environment: env,
    eventManager: entityManager,
   });
  }
 },

 async down(configService: CrudConfigService, entityManager?: EntityManager): Promise<void> {
  const environments = ["development", "staging", "production"];
  const configurationsToRemove = [
   { name: "DEBUG_MODE", section: "app-settings" },
   { name: "API_RATE_LIMIT", section: "api-settings" },
  ];

  for (const config of configurationsToRemove) {
   for (const environment of environments) {
    try {
     await configService.delete({
      section: config.section,
      name: config.name,
      environment: environment,
      eventManager: entityManager,
     });
    } catch (error) {
     console.warn(
      `Failed to delete config ${config.section}:${config.name}:${environment} during rollback`,
     );
    }
   }
  }
 },
};

Advanced Migration Configuration

Configure migrations with custom options:

CrudConfigModule.registerAsync({
 imports: [ConfigModule],
 inject: [ConfigService],
 useFactory: async (configService: ConfigService) => ({
  environment: configService.get("NODE_ENV", "development"),

  migrationOptions: {
   isEnabled: true,
   shouldRunOnStartup: true,
   useTransaction: true,
   stuckMigrationTimeoutMinutes: 60, // Custom timeout

   migrations: [
    initialAppConfigMigration,
    environmentSpecificConfigMigration,
    // Add more migrations in order
   ],
  },

  // Other dynamic options...
 }),
 // Static options for entities and controllers
 staticOptions: {
  migrationEntityOptions: {
   tableName: "my_migrations", // Custom table name must be in staticOptions
   maxNameLength: 256,
  },
  controllersOptions: {
   section: { isEnabled: true },
   data: { isEnabled: true },
  },
 },
});

Migration Best Practices

  1. Naming Convention: Use descriptive names with sequence numbers

    • 001_initial_app_config
    • 002_add_feature_flags
    • migration1, config_setup
  2. Retry safety: Use set() as the upsert for a configuration key

    await configService.set({ eventManager: entityManager, ...properties });
  3. Error Handling: Always handle errors gracefully

    try {
     await configService.set({ eventManager: entityManager, ...properties });
    } catch (error) {
     console.error("Migration failed:", error);
     throw error; // Re-throw to mark migration as failed
    }
  4. Rollback Support: Always implement the down method

    async down(configService: CrudConfigService, entityManager?: EntityManager): Promise<void> {
      // Implement rollback logic
    }
  5. Environment Awareness: Use environment-specific configurations

    const currentEnv = process.env.NODE_ENV || "development";
    await configService.set({
     eventManager: entityManager,
     environment: currentEnv,
     // ... other options
    });

Migration Monitoring

Monitor migration execution with logging:

import { EConfigMigrationStatus } from "@elsikora/nestjs-crud-config";

@Injectable()
export class MigrationMonitorService {
 constructor(private readonly migrationService: ConfigMigrationService) {}

 async getMigrationStatus(): Promise<void> {
  const migrations = await this.migrationService.getExecutedMigrations();

  const completed = migrations.filter((m) => m.status === EConfigMigrationStatus.COMPLETED);
  const failed = migrations.filter((m) => m.status === EConfigMigrationStatus.FAILED);
  const stuck = migrations.filter((m) => m.status === EConfigMigrationStatus.STUCK);

  console.log(
   `Migrations - Completed: ${completed.length}, Failed: ${failed.length}, Stuck: ${stuck.length}`,
  );
 }

 async getFailedMigrations(): Promise<IConfigMigration[]> {
  const migrations = await this.migrationService.getExecutedMigrations();
  return migrations.filter((m) => m.status === EConfigMigrationStatus.FAILED);
 }
}

Testing Migrations

Test your migrations in different environments:

describe("Initial App Config Migration", () => {
 let configService: CrudConfigService;
 let migration: IConfigMigrationDefinition;

 beforeEach(async () => {
  // Setup test environment
  migration = initialAppConfigMigration;
 });

 it("should create required configurations", async () => {
  await migration.up(configService);

  const appName = await configService.get({
   section: "app-settings",
   name: "APP_NAME",
   environment: "default",
  });

  expect(appName.value).toBe("My Application");
 });

 it("should rollback configurations", async () => {
  await migration.up(configService);
  await migration.down(configService);

  await expect(
   configService.get({
    section: "app-settings",
    name: "APP_NAME",
    environment: "default",
   }),
  ).rejects.toThrow();
 });
});

📚 API Documentation

The module automatically generates REST API endpoints with customizable paths:

Configuration Sections (default: /config/section)

  • GET /config/section - List all sections
  • POST /config/section - Create a new section
  • GET /config/section/:id - Get section by ID
  • PUT /config/section/:id - Update section
  • DELETE /config/section/:id - Delete section

Request Body for POST/PUT:

{
 "name": "api-settings",
 "description": "API configuration settings"
}

Configuration Data (default: /config/data)

  • GET /config/data - List all configuration data
  • POST /config/data - Create new configuration
  • GET /config/data/:id - Get configuration by ID
  • PUT /config/data/:id - Update configuration
  • DELETE /config/data/:id - Delete configuration

Request Body for POST/PUT:

{
 "name": "API_KEY",
 "value": "your-secret-key",
 "environment": "production",
 "description": "Production API key",
 "isEncrypted": true,
 "section": { "id": "section-uuid-here" }
}

Customizing API Endpoints

CrudConfigModule.register({
 controllersOptions: {
  section: {
   properties: {
    path: "api/v1/settings/sections",
    name: "CustomSectionController",
    swagger: {
     tags: ["Configuration Sections"],
    },
   },
  },
  data: {
   properties: {
    path: "api/v1/settings/data",
    routes: {
     DELETE: { generation: { isEnabled: false } }, // Disable deletion
    },
   },
  },
 },
});

Automator 3 route options use generation.isEnabled for route generation. Relation loading uses TypeORM relationLoadStrategy values ("query" or "join"); the built-in ConfigData section relation uses "query".

🗄️ Database Schema

The module creates two main tables with the following default structure:

Configuration Sections Table (config_section)

CREATE TABLE config_section (
  id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
  name VARCHAR(128) NOT NULL UNIQUE,
  description VARCHAR(512),
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

Configuration Data Table (config_data)

CREATE TABLE config_data (
  id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
  name VARCHAR(128) NOT NULL,
  value VARCHAR(8192) NOT NULL,
  environment VARCHAR(64) NOT NULL,
  description VARCHAR(512),
  is_encrypted BOOLEAN DEFAULT FALSE,
  section_id UUID NOT NULL REFERENCES config_section(id) ON DELETE CASCADE,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  UNIQUE(name, environment, section_id)
);

🔧 Advanced Configuration

Encryption Support

The module provides built-in AES-256-GCM encryption for sensitive configuration values:

// Enable encryption globally
CrudConfigModule.register({
 encryptionOptions: {
  isEnabled: true,
  encryptionKey: process.env.CONFIG_ENCRYPTION_KEY, // 32+ character key
 },
});

// When encryption is enabled, all values are encrypted automatically
await configService.set({
 section: "database",
 name: "DB_PASSWORD",
 value: "my-secret-password",
});

// Retrieve and decrypt automatically
const config = await configService.get({
 section: "database",
 name: "DB_PASSWORD",
});

console.log(config.value); // Automatically decrypted value
console.log(config.isEncrypted); // true

Transaction and Duplicate Protection

CrudConfigService.set() owns a named Automator transaction when called without eventManager. When a migration supplies its owner manager, all generated ConfigSection and ConfigData service operations join that same transaction.

The package does not require consumer EventEmitterModule wiring. ConfigData uniqueness is enforced by the database across name, environment, and section; Automator maps a conflicting generated create or update to 409 CONFIGDATA_DUPLICATE_KEY. Put application-specific validation or auditing in the application service/lifecycle layer rather than a package before-insert event.

Headless Mode (Without Controllers)

CrudConfigModule.register({
 controllersOptions: {
  section: { isEnabled: false },
  data: { isEnabled: false },
 },
});

This is perfect for:

  • Background services that only need programmatic access
  • Microservices that manage config through message queues
  • Applications with custom GraphQL or gRPC interfaces

Working with Multiple Environments

// multi-env.service.ts
@Injectable()
export class MultiEnvironmentService {
 constructor(private readonly configService: CrudConfigService) {}

 async setupEnvironmentConfigs() {
  const environments = ["development", "staging", "production"];

  for (const env of environments) {
   await this.configService.set({
    section: "database",
    name: "DATABASE_URL",
    environment: env,
    value: `postgres://localhost:5432/${env}_db`,
    description: `Database URL for ${env} environment`,
   });
  }
 }
}

🛣 Roadmap

| Task / Feature | Status | | --------------------------------------------- | -------------- | | Core dynamic entity system | ✅ Done | | TypeORM integration with all databases | ✅ Done | | Hierarchical configuration (sections/data) | ✅ Done | | Full CRUD operations with REST API | ✅ Done | | Swagger/OpenAPI documentation | ✅ Done | | Multi-environment support | ✅ Done | | Named Automator transaction ownership | ✅ Done | | Caching system with TTL | ✅ Done | | Custom table names and prefixes | ✅ Done | | Validation and constraints | ✅ Done | | NestJS CRUD Automator integration | ✅ Done | | TypeScript interfaces and types | ✅ Done | | AES-256-GCM encryption support | ✅ Done | | Async module registration | ✅ Done | | Auto-section creation | ✅ Done | | GraphQL API endpoints | 🚧 In Progress | | Configuration versioning and history | 🚧 In Progress | | Role-based access control (RBAC) | 🚧 In Progress | | Configuration templates and inheritance | 🚧 In Progress | | Real-time configuration updates via WebSocket | 🚧 In Progress | | Configuration validation schemas | 🚧 In Progress | | Bulk import/export functionality | 🚧 In Progress | | Configuration diff and merge tools | 🚧 In Progress | | Audit logging and change tracking | 🚧 In Progress | | Configuration backup and restore | 🚧 In Progress | | Integration with external secret managers | 🚧 In Progress |

❓ FAQ

What databases are supported?

The module supports any database that TypeORM supports, including:

  • PostgreSQL - Recommended for production
  • MySQL/MariaDB - Popular choice for web applications
  • SQLite - Perfect for development and testing
  • Microsoft SQL Server - Enterprise database support
  • Oracle - Enterprise-grade database
  • MongoDB - NoSQL document database
  • CockroachDB - Distributed SQL database

How does this compare to environment variables?

While environment variables are great for simple configurations, this module provides:

  • Database persistence - Configurations survive container restarts
  • Runtime updates - Change configurations without redeployment
  • Hierarchical organization - Group related configurations
  • Multi-environment support - Manage dev/staging/prod from one place
  • Encryption support - Secure sensitive data
  • REST API - Manage configurations programmatically
  • Audit trails - Track configuration changes

Can I migrate from environment variables?

Yes! You can easily migrate by programmatically setting configurations during application startup:

async function migrateFromEnvVars() {
 const configs = [
  { section: "database", name: "DATABASE_URL", value: process.env.DATABASE_URL },
  { section: "api", name: "API_KEY", value: process.env.API_KEY },
  // ... more configurations
 ];

 for (const config of configs) {
  await configService.set(config);
 }
}

How do I handle sensitive configuration data?

The module provides built-in AES-256-GCM encryption support:

CrudConfigModule.register({
 encryptionOptions: {
  isEnabled: true,
  encryptionKey: process.env.CONFIG_ENCRYPTION_KEY,
 },
});

Sensitive values are automatically encrypted before storage and decrypted when retrieved.

Can I use this with microservices?

Absolutely! The module is perfect for microservice architectures:

  • Centralized configuration - All services can share the same config database
  • Service-specific sections - Organize configurations by service
  • Environment isolation - Separate dev/staging/prod configurations
  • Dynamic updates - Update configurations without service restarts

How do I customize table names and field sizes?

The module provides extensive customization options:

CrudConfigModule.register({
 entityOptions: {
  tablePrefix: "myapp_",
  configSection: {
   tableName: "configuration_sections",
   maxNameLength: 256,
   maxDescriptionLength: 1024,
  },
  configData: {
   tableName: "configuration_values",
   maxValueLength: 16384, // 16KB values
   maxEnvironmentLength: 128,
   maxNameLength: 256,
   maxDescriptionLength: 1024,
  },
 },
});

What happens if the database is unavailable?

The module includes caching to handle temporary database outages:

  • In-memory cache - Recently accessed configurations are cached
  • Configurable TTL - Control how long configurations are cached
  • Graceful degradation - Falls back to cached values when database is unavailable

Can I use this without REST API endpoints?

Yes! The module supports "headless mode" where controllers are disabled:

CrudConfigModule.register({
 controllersOptions: {
  section: { isEnabled: false },
  data: { isEnabled: false },
 },
});

Is this production-ready?

Yes! The module is built with production use in mind:

  • Type-safe - Full TypeScript support prevents runtime errors
  • Battle-tested - Built on proven technologies (NestJS, TypeORM)
  • Scalable - Works with enterprise databases
  • Secure - Built-in encryption and validation
  • Observable - Comprehensive logging and monitoring hooks

🔒 License

This project is licensed under MIT License

Copyright (c) 2025 ElsiKora

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.