DEV Community

depak379mandal
depak379mandal

Posted on

Load .env using Config Module in NestJS

Love to work with you, You can hire me on Upwork.

We are moving towards something that will give us a very good idea how to maintain our all global environment variable. NestJs have solution library for that.

npm i --save @nestjs/config
Enter fullscreen mode Exit fullscreen mode

We will have config folder inside modules that will contain all the config from .env in separate files according to concern, i.e., database env variables will be in database.config.ts and get imported from .env file from local. @nestjs/config loads data from .env file, but we can actually define from it can fetch more variables according to our requirement. But I would suggest to use only .env as it is very easy to understand and maintain in between developers.

Below just an example how you can use and register Config Module from NestJS standard config library to maintain the segregation between different types of .env variable and can use them accordingly in any module as ConfigModule. Starting this process with defining some config variables in src/modules/config/app.config.ts and src/modules/config/database.config.ts. app.config.ts will contain some normal global metadata for app and database.config.ts will contain data related to database. They both are defined below.

// src/modules/config/app.config.ts

import { registerAs } from '@nestjs/config';

export default registerAs('app', () => ({
  nodeEnv: process.env.NODE_ENV,
  name: process.env.APP_NAME,
  workingDirectory: process.env.PWD || process.cwd(),
  port: process.env.APP_PORT,
}));
Enter fullscreen mode Exit fullscreen mode
// src/modules/config/database.config.ts

import { registerAs } from '@nestjs/config';

export default registerAs('database', () => ({
  url: process.env.DATABASE_URL,
}));
Enter fullscreen mode Exit fullscreen mode

And inside src/modules/config/index.ts we will export them as an array So they can be loaded in ConfigModule in app module.

// src/modules/config/index.ts

import appConfig from './app.config';
import databaseConfig from './database.config';

export const configLoads = [databaseConfig, appConfig];
Enter fullscreen mode Exit fullscreen mode

Now we have to load them in app module, App module is center of everything, So to use every module in system you have to register it there. We will import config module there, and we will go with two types of module, both are global and normal modules. Both will have different array, so we will now have very clear understanding which modules’ feature can be used as global.

// src/modules/app/app.module.ts

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

const modules = [];

export const global_modules = [
  ConfigModule.forRoot({
    load: configLoads,
    isGlobal: true,
    envFilePath: ['.env'],
  }),
];

@Module({
  imports: [...global_modules, ...modules],
})
export class AppModule {}
Enter fullscreen mode Exit fullscreen mode

To define ConfigModule as global, we have passed isGlobal as true and we also passed our configLoads with envFilePath but you don’t have to pass .env separately, it automatically loads .env for us. We have used forRoot function to registering the module. Most of the module does provide us these type of interface to register them.

Now time to use them for use cases, We are going to use port from app config in main.ts to set port dynamically from .env file for application.

// src/main.ts

import { NestFactory } from '@nestjs/core';
import { AppModule } from './modules/app/app.module';
import { ConfigService } from '@nestjs/config';

async function bootstrap() {
  // created application instance using NestFactory
  const app = await NestFactory.create(AppModule);

  // getting configService from application 
  // to fetch port from app.config.ts config load
  const configService = app.get(ConfigService);

  // used the port value here
  await app.listen(configService.get('app.port') || 8000);
}
bootstrap();
Enter fullscreen mode Exit fullscreen mode

Now we can define .env file in our working directory that will hold our environment variables that can be used in further application.
Below is a sample .env file you can use.

NODE_ENV=development
APP_PORT=8000
APP_NAME="NestJS Series"

# Database Configuration
DATABASE_URL=postgresql://localhost:5432
Enter fullscreen mode Exit fullscreen mode

After adding .env file run npm run start:dev it will show you output, you can see it is running without error.

Image description

In the next article, we will see how we can utilize particular .env variables inside other modules using ConfigService injection through TypeORM introduction.

Thank you for reading, see you in the next.

Top comments (0)