0
0
NestJSframework~30 mins

Shared modules in NestJS - Mini Project: Build & Apply

Choose your learning style9 modes available
Creating and Using Shared Modules in NestJS
📖 Scenario: You are building a NestJS application that needs to share a simple service across multiple modules. To avoid repeating code, you will create a shared module that exports this service so other modules can use it easily.
🎯 Goal: Build a shared module in NestJS that provides a LoggerService. Then import this shared module into another module to use the LoggerService.
📋 What You'll Learn
Create a LoggerService class with a method log(message: string) that logs messages.
Create a SharedModule that provides and exports LoggerService.
Create a FeatureModule that imports SharedModule.
Inject LoggerService into a service inside FeatureModule and use its log method.
💡 Why This Matters
🌍 Real World
Shared modules are common in real NestJS apps to provide reusable services like logging, configuration, or database access across many parts of the app.
💼 Career
Understanding shared modules is essential for building scalable and maintainable backend applications with NestJS, a popular framework used in many companies.
Progress0 / 4 steps
1
Create the LoggerService
Create a class called LoggerService with a method log(message: string) that logs the message to the console using console.log.
NestJS
Need a hint?

Use console.log inside the log method to print the message.

2
Create SharedModule that provides and exports LoggerService
Create a NestJS module called SharedModule that provides and exports the LoggerService. Use the @Module decorator with providers and exports arrays containing LoggerService.
NestJS
Need a hint?

Use @Module decorator from @nestjs/common and include LoggerService in both providers and exports.

3
Create FeatureModule that imports SharedModule
Create a NestJS module called FeatureModule that imports the SharedModule. Use the @Module decorator with an imports array containing SharedModule.
NestJS
Need a hint?

Use @Module decorator and add SharedModule to the imports array.

4
Inject LoggerService into a service in FeatureModule and use it
Create a service class called FeatureService inside FeatureModule. Inject LoggerService in its constructor and call this.logger.log('FeatureService initialized') inside the constructor.
NestJS
Need a hint?

Use @Injectable() on FeatureService, inject LoggerService in the constructor, and call log method.