0
0
NestJSframework~30 mins

Custom configuration files in NestJS - Mini Project: Build & Apply

Choose your learning style9 modes available
Custom configuration files in NestJS
📖 Scenario: You are building a NestJS application that needs to load custom configuration settings from a separate file. This helps keep your app settings organized and easy to change without touching the main code.
🎯 Goal: Create a custom configuration file and load it into your NestJS app using the ConfigModule. You will define a config file, import it, and access its values in a service.
📋 What You'll Learn
Create a configuration file named app.config.ts exporting a function returning an object with a port number and database object with host and port.
Import the custom config file into the ConfigModule.forRoot() using the load option.
Inject ConfigService into a service and read the port and database.host values.
Log the loaded configuration values inside the service constructor.
💡 Why This Matters
🌍 Real World
Custom configuration files help keep app settings organized and separate from code. This makes apps easier to maintain and configure for different environments.
💼 Career
Many backend jobs require managing app settings cleanly. Knowing how to use NestJS ConfigModule with custom config files is a valuable skill for building scalable, maintainable applications.
Progress0 / 4 steps
1
Create the custom configuration file
Create a file named app.config.ts that exports a default function returning an object with these exact properties: port set to 3000, and database as an object with host set to 'localhost' and port set to 5432.
NestJS
Need a hint?

Use export default () => ({ ... }) to export the config object.

2
Load the custom config in ConfigModule
In your main module file (e.g., app.module.ts), import ConfigModule from @nestjs/config. Then, call ConfigModule.forRoot() with the load option set to an array containing the imported app.config function.
NestJS
Need a hint?

Use ConfigModule.forRoot({ load: [appConfig] }) inside the imports array.

3
Inject ConfigService and read config values
Create a service named AppService. Inject ConfigService from @nestjs/config in its constructor. Inside the constructor, read the port value using this.configService.get('port') and the database.host value using this.configService.get('database.host'). Store these values in class properties named appPort and dbHost respectively.
NestJS
Need a hint?

Use this.configService.get('port') and this.configService.get('database.host') inside the constructor.

4
Log the configuration values in the service
Inside the AppService constructor, add two console.log statements to print the appPort and dbHost values with these exact messages: App running on port: {appPort} and Database host: {dbHost}.
NestJS
Need a hint?

Use template strings inside console.log to show the values.