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

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)