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

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';

  4. 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(),

  5. 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.


1. 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` });

2. 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


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