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