- Add @nestjs/config library to your dependencies in package.json
$ yarn add @nestjs/config
- 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, }));
- 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, }));
- 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];
- 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 {}
- 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();
- Add .env
NODE_ENV=development APP_PORT=8000 APP_NAME="NestJS Series" # Database Configuration DATABASE_URL=postgresql://localhost:5432
- Run the server in development mode
$ yarn run start:dev
Last active
September 24, 2024 05:01
-
-
Save programmerShinobi/af338805da400a8809b29e1b18695dcd to your computer and use it in GitHub Desktop.
Load .env using Config Module in NestJS (NestJS Series 02)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment