I've organized my project structure like this:
https://i.sstatic.net/WRKCI.png
Using nx with nest. In the app.module.ts
file, I've set up the ConfigModule
to read the .env
file based on the NODE_ENV
variable, which is then used to connect to MongoDB.
const envFilePath = `../envs/.env.${process.env.NODE_ENV.toLowerCase() || 'development'}`;
@Module({
imports: [
ConfigModule.forRoot({
envFilePath,
isGlobal: true
}),
MongooseModule.forRootAsync({
imports: [ConfigModule],
inject: [ConfigService],
useFactory: async (configService: ConfigService) => {
console.log(configService.get<string>('MONGO_URI'));
return {
uri: configService.get<string>('MONGO_URI')
};
}
})
],
controllers: [AppController],
providers: [AppService]
})
export class AppModule {}
However, the issue is that
configService.get<string>('MONGO_URI')
always returns undefined
.The reason for this is that when you output the constant __filename
to the console, its value will be <absolute-path>\dist\apps\backend\main.js
. This means all paths in the file are referenced relative to the dist
folder located at the root of the nx project.
Question: How can I make env files accessible through relative paths from the src directory without creating a path from dist to src, as it might be unreliable and incorrect?
I considered storing configs in .ts
files, but I'm not keen on this option as those files should contain code rather than just data.