Using TypeORM with env in NestJS

Seobs
2 min readFeb 9, 2023

The way I initially used TypeORM was to use TypeOrmModule in an AppModule.

And You can be found in the official documentation.

import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';

@Module({
imports: [
TypeOrmModule.forRoot({
type: 'mysql',
host: 'localhost',
port: 3306,
username: 'root',
password: 'root',
database: 'test',
entities: [],
synchronize: true,
}),
],
})
export class AppModule {}

I’m trying to separate TypeORM configuration into different files and use .env.

First, I created database.config.js in config folder.
And I used Configservice to use .env.

import { Injectable } from '@nestjs/common';
import { TypeOrmModuleOptions, TypeOrmOptionsFactory } from '@nestjs/typeorm';
import { ConfigService } from '@nestjs/config';

@Injectable()
export class TypeOrmConfigService implements TypeOrmOptionsFactory {
constructor(private configService: ConfigService) {}

createTypeOrmOptions(): TypeOrmModuleOptions {
return {
type: 'mysql',
host: this.configService.get<string>('DB_HOST'),
port: +this.configService.get<number>('DB_PORT'),
username: this.configService.get<string>('DB_NAME'),
password: this.configService.get<string>('DB_PASSWORD'),
database: this.configService.get<string>('DB_DATABASE'),
entities: ['dist/**/**/*.entity.{ts,js}'],
synchronize: false,
};
}
}

The AppModule was also modified.

@Module({
imports: [
ConfigModule.forRoot(),
TypeOrmModule.forRootAsync({
imports: [ConfigModule],
useClass: TypeOrmConfigService,
}),
],
providers: [AppService],
controllers: [AppController],
})
export class AppModule {
constructor(private dataSource: DataSource) {}
}

That’s it.

There are many ways, and my solution is different.

You can use process.env instead of ConfigService.
And I didn’t use the global option.

Even in the AppModule I didn’t use useExisting but useClass.

I hope you solve it in your own way.

--

--