0
0
NestJSframework~30 mins

Configuration namespaces in NestJS - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Configuration Namespaces in NestJS
📖 Scenario: You are building a NestJS application that needs to manage different configuration settings for database and API. To keep things organized, you will use configuration namespaces.
🎯 Goal: Create a NestJS configuration setup that uses namespaces to separate database and api settings, then access these settings in a service.
📋 What You'll Learn
Create a configuration object with database and api namespaces
Add a configuration module using ConfigModule.forRoot() with the namespaces
Access the database.host and api.key values in a service using ConfigService
Use the namespaces properly to retrieve the correct configuration values
💡 Why This Matters
🌍 Real World
Many real-world NestJS applications need to organize configuration settings for different parts like database, API, and authentication. Using namespaces keeps these settings clear and manageable.
💼 Career
Understanding configuration namespaces and how to access them is important for backend developers working with NestJS to build scalable and maintainable applications.
Progress0 / 4 steps
1
Create configuration namespaces
Create a constant called configuration that returns an object with two namespaces: database containing host set to 'localhost' and port set to 5432, and api containing key set to '12345' and timeout set to 5000.
NestJS
Need a hint?

Use a function that returns an object with database and api keys, each having their own settings.

2
Configure ConfigModule with namespaces
Import ConfigModule from @nestjs/config and call ConfigModule.forRoot() with the load option set to an array containing the configuration function.
NestJS
Need a hint?

Use ConfigModule.forRoot() and pass load with your configuration function inside an array.

3
Access configuration values in a service
Create a class called AppService with a constructor that injects ConfigService from @nestjs/config. Inside the class, create a method getDatabaseHost() that returns the database host by calling this.configService.get('database.host'), and a method getApiKey() that returns the API key by calling this.configService.get('api.key').
NestJS
Need a hint?

Inject ConfigService in the constructor and use get() with the full path to access nested config values.

4
Complete module setup with ConfigModule import
Create a class called AppModule decorated with @Module from @nestjs/common. Inside the decorator, add imports with an array containing ConfigModule.forRoot({ load: [configuration] }), and providers with an array containing AppService.
NestJS
Need a hint?

Use the @Module decorator to import ConfigModule.forRoot() with your configuration and provide AppService.