I'm trying to setup configuration for my NestJS app by following some of the following documentation:
Config: https://docs.nestjs.com/techniques/configuration
TypeORM: https://docs.nestjs.com/techniques/database#async-configuration
I've added a .env file to the root of my project (same level as package.json
) with the following values:
DB_URL=localhost
DB_USER=root
DB_PASSWORD=root
DB_NAME=test_db
In my app.module.ts, I import the following modules:
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { AppController } from './app.controller';
import { AppService } from './app.service';
@Module({
imports: [
ConfigModule.forRoot(),
TypeOrmModule.forRootAsync({
imports: [ConfigModule],
useFactory: (configService: ConfigService) => {
// The value logged below is undefined'
console.log(`DB URL: ${configService.get('DB_URL')}`);
return {
type: 'mysql',
host: configService.get('DB_URL'),
port: 3306,
username: configService.get('DB_USER'),
password: configService.get('DB_PASSWORD'),
database: configService.get('DB_NAME'),
entities: ['dist/**/*.entity{.ts,.js}'],
synchronize: false,
migrations: ['dist/migrations/*{.js}'],
cli: {
migrationsDir: 'migrations',
},
};
},
inject: [ConfigService],
}),
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
As noted above, the value retrieved by configService.get('DB_URL') is undefined
. Was hoping for any help/advice on how to set up the configuration so that I could read the values in my .env
file when starting up the application.