Drizzle forRootAsync with ConfigService
NestJS Drizzle forRootAsync with ConfigService builds the database config at startup, from useFactory, useClass or useExisting and any provider you inject.
DrizzleCrudModule.forRootAsync({ imports, inject, useFactory }) is the async form of forRoot for NestJS Drizzle apps that read their config from ConfigService. Nest calls your useFactory at startup with the providers listed in inject, and the object it returns (or resolves to) is the same DrizzleCrudConfig that forRoot takes, with the same defaults filled in. Since 3.7.0 it also takes useClass or useExisting, the usual Nest way to build options from a class.
Give exactly one of useFactory, useClass or useExisting
With none of them, or with more than one, forRootAsync throws when the module is declared,
and the message names what it got. Before 3.7.2 useFactory silently won over the other two.
What does forRootAsync take?
DrizzleCrudModule.forRootAsync(options: DrizzleCrudAsyncOptions): DynamicModule
interface DrizzleCrudAsyncOptions {
imports?: any[];
inject?: any[];
useFactory?: (...deps: any[]) => DrizzleCrudConfig | Promise<DrizzleCrudConfig>;
useClass?: Type<DrizzleCrudOptionsFactory>;
useExisting?: Type<DrizzleCrudOptionsFactory>;
}
interface DrizzleCrudOptionsFactory {
createDrizzleCrudOptions(): DrizzleCrudConfig | Promise<DrizzleCrudConfig>;
}useFactoryOptional(...deps) => config
useClassOptionalType<DrizzleCrudOptionsFactory>
useExistingOptionalType<DrizzleCrudOptionsFactory>
injectOptionalany[]
Defaults to []
importsOptionalany[]
Defaults to []
The module is global, exactly like forRoot, and exports the same tokens (DRIZZLE_DB, DRIZZLE_CRUD_CONFIG, DRIZZLE_CONNECTION, CrudEventBus).
How do I read the config from ConfigService?
Install @nestjs/config
pnpm add @nestjs/configInject ConfigService into the factory
import { Module } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { DrizzleCrudModule } from '@avytrix/nestjs-drizzle-crud';
import * as schema from './db/schema';
@Module({
imports: [
ConfigModule.forRoot({ isGlobal: true }),
DrizzleCrudModule.forRootAsync({
imports: [ConfigModule],
inject: [ConfigService],
useFactory: (config: ConfigService) => ({
dialect: 'postgresql',
connectionString: config.getOrThrow<string>('DATABASE_URL'),
schema,
defaults: {
pagination: { defaultLimit: 20, maxLimit: 100 },
},
}),
}),
],
})
export class AppModule {}getOrThrow stops startup with a clear error when the variable is missing, instead of failing later on the first query.
How do I build my own Drizzle instance in the factory?
Return db instead of connectionString. Use this on SQLite, libSQL and D1, or for a driver option that connection (pool size, SSL, idle timeout) does not cover:
import { Module } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { drizzle } from 'drizzle-orm/postgres-js';
import postgres from 'postgres';
import { DrizzleCrudModule } from '@avytrix/nestjs-drizzle-crud';
import * as schema from './db/schema';
@Module({
imports: [
ConfigModule.forRoot({ isGlobal: true }),
DrizzleCrudModule.forRootAsync({
inject: [ConfigService],
useFactory: (config: ConfigService) => {
const client = postgres(config.getOrThrow<string>('DATABASE_URL'), {
max: config.get<number>('DB_POOL_SIZE', 10),
});
return { dialect: 'postgresql', db: drizzle(client, { schema }) };
},
}),
],
})
export class AppModule {}A db you pass in is yours: the module does not close it on shutdown. Only a connection the module built from connectionString is closed for you.
Can the factory be async?
Yes. Return a promise when you fetch a value at startup, for example a password from a secrets manager:
DrizzleCrudModule.forRootAsync({
imports: [SecretsModule],
inject: [ConfigService, SecretsService],
useFactory: async (config: ConfigService, secrets: SecretsService) => ({
dialect: 'postgresql',
connectionString: await secrets.get('DATABASE_URL'),
schema,
sql: { caseSensitive: config.get<boolean>('CASE_SENSITIVE_FILTERS', false) },
}),
})SecretsModule and SecretsService stand for your own module. Nest waits for the promise before it builds any service, so a rejected promise stops startup.
How do I use a config class with useClass?
Implement DrizzleCrudOptionsFactory and pass the class as useClass. The module registers it, injects its constructor and calls createDrizzleCrudOptions():
import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import type {
DrizzleCrudConfig,
DrizzleCrudOptionsFactory,
} from '@avytrix/nestjs-drizzle-crud';
import * as schema from './db/schema';
@Injectable()
export class CrudConfigService implements DrizzleCrudOptionsFactory {
constructor(private readonly config: ConfigService) {}
createDrizzleCrudOptions(): DrizzleCrudConfig {
return {
dialect: 'postgresql',
connectionString: this.config.getOrThrow<string>('DATABASE_URL'),
connection: { poolSize: this.config.get<number>('DB_POOL_SIZE', 10) },
schema,
};
}
}DrizzleCrudModule.forRootAsync({ useClass: CrudConfigService })ConfigService resolves here because ConfigModule is global. For a provider from a module that is not global, add that module to imports.
How do I reuse a provider with useExisting?
When the config class is already a provider in another module, export it from there and pass useExisting. The module asks that instance for the config instead of creating its own:
@Module({ providers: [CrudConfigService], exports: [CrudConfigService] })
export class CrudConfigModule {}
DrizzleCrudModule.forRootAsync({
imports: [CrudConfigModule],
useExisting: CrudConfigService,
})When should I use forRoot instead?
Use forRoot when the config is a plain object you can build when the module file loads. Use forRootAsync when any of these hold:
- The connection string goes through
ConfigServiceand its validation. - The Drizzle instance is built from config values, such as the pool size.
- The config depends on another provider: feature flags, a secrets manager, a tenant registry.
Common questions
Yes, since 3.7.0. The class implements DrizzleCrudOptionsFactory and returns the config from createDrizzleCrudOptions(). useClass creates the instance, useExisting reuses one exported by a module in imports.
No. With isGlobal: true, ConfigService resolves without it. Listing it does no harm.
Yes. Nest waits for it before building the connection and the services, and a rejection stops startup.
Yes. The object your factory returns goes through the same normalization, so soft delete, timestamps, pagination and the sql flags get the same defaults.
Next steps
forFeature
Bind each service to its table and override defaults per entity.
NestJS Drizzle module forRoot options
Every option and its default.
Config types
The full DrizzleCrudConfig type.
NestJS Drizzle module forRoot options
Configure the NestJS Drizzle module with forRoot. Set the connection, dialect, soft delete, timestamps, pagination and SQL defaults once in AppModule.
SQLite, libSQL and Cloudflare D1
Use NestJS with Drizzle on SQLite, libSQL (Turso) or Cloudflare D1. What works, what is a 400, and why D1 cannot run bulk writes or nested creates.