Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

1.8K
Views
NestJS - How to use .env variables in main app module file for database connection

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:mypassword@myhost.net?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],
})
over 4 years ago · Santiago Trujillo
5 answers
Answer question

0

MongooseModule.forRootAsync({
  imports: [ConfigModule],
  useFactory: async (configService: ConfigService) => ({
    uri: configService.get<string>('MONGODB_URI'),
  }),
  inject: [ConfigService],
});
over 4 years ago · Santiago Trujillo Report

0

From Nestjs docs here - https://docs.nestjs.com/techniques/configuration

These steps worked for me with MySQL and TypeORM.

  1. Install Nestjs config module - npm i --save @nestjs/config. It relies on dotenv

  2. Create a .env file in your root folder and add your key/value pairs e.g. DATABASE_USER=myusername

  3. Open app.module.ts and import the config module

    import { ConfigModule } from '@nestjs/config';
  1. 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(),
  1. 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.

over 4 years ago · Santiago Trujillo Report

0

You need to use the MongooseModule.forRootAsync(() => {...}) instead of MongooseModule.forRoot(...)

This makes MongooseModule wait for its IOC dependencies.

See: https://docs.nestjs.com/techniques/mongodb#async-configuration

over 4 years ago · Santiago Trujillo Report

0

1. Keeping using ConfigModule

You need to set NODE_ENV in npm scripts so that it can be used to load an env file based on the env.

"scripts": {
  "start:local": "NODE_ENV=local npm run start"
  "start:dev": "NODE_ENV=dev npm run start"
}

Now you can just use the ConfigModule:

@Module({
  imports: [
    ConfigModule.forRoot({ envFilePath: `${process.env.NODE_ENV}.env` }), 
MongooseModule.forRoot(`mongodb+srv://${process.env.DB_USER}:${process.env.DB_PASS}@myhost.net?retryWrites=true&w=majority&db=dbname`, { useNewUrlParser: true, dbName: 'dbname' })
    ...
})

2. Using dotenv

npm install dotenv

Add some scripts to your package.json to set what env you are in.

"scripts": {
  ...
  "start:local": "NODE_ENV=local npm run start"
  "start:dev": "NODE_ENV=dev npm run start"
}

Import dotenv in main.ts file. Make sure you do it at the top of the file.

require('dotenv').config({ path: `../${process.env.NODE_ENV}.env` });

3. Using env-cmd

You can use env-cmd npm package.

npm install env-cmd

And add some commands for different envs in package.json, for example:

"scripts": {
  ...
  "start:local": "env-cmd -f local.env npm run start"
  "start:dev": "env-cmd -f dev.env npm run start"
}
...

Now you can use the env variables, for example:

MongooseModule.forRoot(`mongodb+srv://${process.env.DB_USER}:${process.env.DB_PASS}@myhost.net?retryWrites=true&w=majority&db=dbname`, { useNewUrlParser: true, dbName: 'dbname' })

process.env.MONGO_CONNECTION_STRING

over 4 years ago · Santiago Trujillo Report

0

By using nestjs/config package:

npm install @nestjs/config

After installing the package, in the app module (app.module.ts file):

import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';

@Module({
  imports: [ConfigModule.forRoot()],
})

export class AppModule {}

After that .env files can be accessed all over the app. Suppose your .env file looks like this.

DB_USER=mohit

to access DB_USER variable use process.env.DB_USER

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!