'Nest JS .env file variables are undefined even though im using ConfigModule
My variables are undefined but im using .env file in the root of the project that same way it is described in the documentation. Also adding condif imported from 'dotenv' works.
import { config } from 'dotenv';
config();
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { PodcastsModule } from './podcasts/podcasts.module';
import { TypeOrmModule } from '@nestjs/typeorm';
import { config } from 'dotenv';
config();
const { HOST, PORT, USER, PASSWORD, DATABASE } = process.env;
@Module({
imports: [
ConfigModule.forRoot(),
PodcastsModule,
TypeOrmModule.forRoot({
type: 'postgres',
host: HOST,
port: parseInt(PORT),
username: USER,
password: PASSWORD,
database: DATABASE,
autoLoadEntities: true,
synchronize: true,
}),
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
Solution 1:[1]
At the time you are destructuring process.env, dotenv.config() has not yet been ran and the process.env has not beed populated. You can either call dotenv.config() as the very first thing in your main.ts file, or you can use asynchronous registration and use the ConfigService inside of TypeormModule.forRootASync() like so:
@Module({
imports: [
ConfigModule.forRoot(),
PodcastsModule,
TypeOrmModule.forRootAsync({
inject: [ConfigService],
useFactory: (config: ConfigService) => ({
type: 'postgres', // you may need to add an `as const` here
host: config.get('HOST'),
port: parseInt(config.get('PORT')),
username: config.get('USER'),
password: config.get('PASSWORD'),
database: config.get('DATABASE'),
autoLoadEntities: true,
synchronize: true,
})
}),
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jay McDoniel |
