Skip to content

Instantly share code, notes, and snippets.

@programmerShinobi
Last active September 24, 2024 05:01
Show Gist options
  • Save programmerShinobi/af338805da400a8809b29e1b18695dcd to your computer and use it in GitHub Desktop.
Save programmerShinobi/af338805da400a8809b29e1b18695dcd to your computer and use it in GitHub Desktop.
Load .env using Config Module in NestJS (NestJS Series 02)

How to Load .env using Config Module in NestJS

  1. Add @nestjs/config library to your dependencies in package.json
    $ yarn add @nestjs/config
  2. Add src/modules/config/app.config.ts
     // 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,
    }));
  3. Add src/modules/config/database.config.ts
    // src/modules/config/database.config.ts
    
    import { registerAs } from '@nestjs/config';
    
    export default registerAs('database', () => ({
      url: process.env.DATABASE_URL,
    }));
  4. Add src/modules/config/index.ts
    // src/modules/config/index.ts
    
    import appConfig from './app.config';
    import databaseConfig from './database.config';
    
    export const configLoads = [databaseConfig, appConfig];
  5. Edit src/modules/app/app.module.ts
    // 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 {}
  6. Edit src/main.ts
    // src/main.ts
    
    import { NestFactory } from '@nestjs/core';
    import { AppModule } from './app.module';
    import { ConfigService } from '@nestjs/config';
    import { Logger } from '@nestjs/common';
    
    async function bootstrap() {
      const log = new Logger(bootstrap.name);
      // create 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);
    
      const PORT = configService.get('app.port') || 8000;
    
      // used the port value here
      await app.listen(PORT);
    
      log.log(
        `NestJS Series (${process.env.npm_package_version}) start on port ${PORT}`,
      );
    }
    bootstrap();
  7. Add .env
    NODE_ENV=development
    APP_PORT=8000
    APP_NAME="NestJS Series"
    
    # Database Configuration
    DATABASE_URL=postgresql://localhost:5432
  8. Run the server in development mode
    $ yarn run start:dev
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment