'Different environments not working in NestJS
I would like to create a new environment for testing my app. I have a .env file and .env.test file.
This is my app.module.ts file:
@Module({
imports: [
ConfigModule.forRoot({
envFilePath: !process.env.NODE_ENV
? '.env'
: `.env.${process.env.NODE_ENV}`,
}),
TypeOrmModule.forRoot({
type: 'postgres',
host: process.env.POSTGRES_HOST,
port: parseInt(<string>process.env.POSTGRES_PORT),
username: process.env.POSTGRES_USER,
password: process.env.POSTGRES_PASSWORD,
database: process.env.POSTGRES_DATABASE,
autoLoadEntities: true,
entities: [User],
synchronize: true,
}),
AuthModule,
],
controllers: [],
providers: [],
})
export class AppModule {}
The problem here is that .env.test is never called, .env always runs even though process.env.NODE_ENV returns test.
And this is how i set up my package.json file:
"start:test": "NODE_ENV=test nest start --watch",
This is how my .env.test file looks like
POSTGRES_HOST=localhost
POSTGRES_PORT=5432
POSTGRES_USER=postgres
POSTGRES_PASSWORD=Random
POSTGRES_DATABASE=db-test
I also tried to hardcode envFilePath: '.env.test', and it still not working. For .env.test file to work i have to rename .env file and then it works fine.
UPDATE!
It works now. What i did was i put
ConfigModule.forRoot({
envFilePath: !process.env.NODE_ENV
? '.env'
: `.env.${process.env.NODE_ENV}`,
}),
in every module i have in my app.
Solution 1:[1]
As you're using the ConfigModule presumably from @nestjs/config you should be using the TypeormModule's forRootAsync method to make sure you use the read .env file.
@Module({
imports: [
ConfigModule.forRoot({
envFilePath: !process.env.NODE_ENV
? '.env'
: `.env.${process.env.NODE_ENV}`,
}),
TypeOrmModule.forRootAsync({
inject: [ConfigService],
useFactory: (config: ConfigService): PostgresConnectionOptions => ({
type: 'postgres' as const,
host: config.get('POSTGRES_HOST'),
port: parseInt(config.get('POSTGRES_PORT')),
username: config.get('POSTGRES_USER'),
password: config.get('POSTGRES_PASSWORD'),
database: config.get('POSTGRES_DATABASE'),
autoLoadEntities: true,
entities: [User],
synchronize: true,
}),
}),
AuthModule,
],
controllers: [],
providers: [],
})
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 |
