How to setup different environment file in nest js using postgresql

2.1k Views Asked by At

I am new this framework. I connected PostgreSQL database using ormconfig file. but I need to configure development environment, production environment, test environment. How to achieve this scenarios. I tried to use config service in my project. but always connected only .env file configuration.

development.env

POSTGRES_HOST=127.0.0.1
POSTGRES_PORT="5432"
POSTGRES_USER=postgres
POSTGRES_PASSWORD='*****'
POSTGRES_DATABASE=testdb123
PORT=4000
2

There are 2 best solutions below

0
On BEST ANSWER

Well, I would recomment to keep .env file under git ignore and have a .env.example with all possible configuration items.

If you like to have a default settings for every env, you can use something like https://www.npmjs.com/package/dotenv-defaults

If you want to use DI & typing as well as env files for each environments, take a look at the nest configuration module

0
On

You could use ormconfig.js and at the top of it add something like this:

require('dotenv').config({
  path: '.env.' + process.env.NODE_ENV
})

Another option is to import ConfigModule like this:

ConfigModule.forRoot({
  load: [config],
  envFilePath: '.env.' + process.env.NODE_ENV
})

And use async configuration for TypeORM:

TypeOrmModule.forRootAsync({
  imports: [ConfigModule],
  useFactory: (configService: ConfigService) => ({
    type: 'mysql',
    host: configService.get('POSTGRES_HOST'),
    port: +configService.get<number>('POSTGRES_PORT'),
    username: configService.get('POSTGRES_USER'),
    password: configService.get('POSTGRES_PASSWORD'),
    database: configService.get('POSTGRES_DATABASE'),
    entities: [__dirname + '/**/*.entity{.ts,.js}'],
    synchronize: configService.get('TYPEORM_SYNC'),
  }),
  inject: [ConfigService],
})

I use a similar async configuration here.