I am working on my first NestJS application, which was working fine with hardcoded database connecting string in app.module.ts
.
But then as per our requirements, I had to pick the database config values from environment files. For that, I followed the configuration documentation on the nestjs documentation website - https://docs.nestjs.com/techniques/configuration
But the issue is that I need to use the .env variables inside the same file for database connection, which is failing.
Here is my original code that was working fine:
@Module({
imports: [
MongooseModule.forRoot(`mongodb+srv://myusername:[email protected]?retryWrites=true&w=majority&db=dbname`, { useNewUrlParser: true, dbName: 'dbname' }),
ProductModule,
CategoryModule,
],
controllers: [
AppController,
HealthCheckController,
],
providers: [AppService, CustomLogger],
})
Now, I wanted to pick those DB values from .env files which are like local.env
, dev.env
etc. depending on the environment. Now, my this code is not working:
@Module({
imports: [
ConfigModule.forRoot({ envFilePath: `${process.env.NODE_ENV}.env` }),
MongooseModule.forRoot(`mongodb+srv://${ConfigModule.get('DB_USER')}:${ConfigModule.get('DB_PASS')}@myhost.net?retryWrites=true&w=majority&db=dbname`, { useNewUrlParser: true, dbName: 'dbname' }),
ProductModule,
CategoryModule,
],
controllers: [
AppController,
HealthCheckController,
],
providers: [AppService, CustomLogger],
})
From Nestjs docs here - https://docs.nestjs.com/techniques/configuration
These steps worked for me with MySQL and TypeORM.
Install Nestjs config module - npm i --save @nestjs/config
. It relies on dotenv
Create a .env file in your root folder and add your key/value pairs e.g. DATABASE_USER=myusername
Open app.module.ts and import the config module
import { ConfigModule } from '@nestjs/config';
Add below line to the imports section of app.module.ts. I added it a the first import. It will load the contents of the .env file automatically.
ConfigModule.forRoot(),
Then you can begin to use the env variables as per the usual process.env.<variable_name> in the database config section e.g.
process.env.DATABASE_USER
For more configuration of the ConfigModule, see the link above. You can use a custom file/path and set the module visible globally.