0
0
NestjsConceptBeginner · 3 min read

What is Provider in NestJS: Explanation and Example

In NestJS, a provider is a class or value that can be injected as a dependency to other classes using Nest's Dependency Injection system. Providers are used to organize and share logic like services, repositories, or helpers across your application.
⚙️

How It Works

Think of a provider in NestJS like a helpful assistant in a kitchen. Instead of every chef having to prepare every ingredient themselves, they ask the assistant to provide what they need. Similarly, a provider is a class or value that NestJS can create and supply to other parts of your app when needed.

Behind the scenes, NestJS uses a system called Dependency Injection. This means when a class needs something (like a service or helper), it declares that need, and NestJS automatically gives it the right provider. This keeps your code clean and easy to manage, like having a well-organized kitchen where everyone knows who to ask for what.

💻

Example

This example shows a simple provider called GreetingService that returns a greeting message. It is injected into a controller to use its functionality.

typescript
import { Injectable, Controller, Get } from '@nestjs/common';

@Injectable()
export class GreetingService {
  getGreeting(): string {
    return 'Hello from GreetingService!';
  }
}

@Controller()
export class AppController {
  constructor(private readonly greetingService: GreetingService) {}

  @Get()
  getHello(): string {
    return this.greetingService.getGreeting();
  }
}

// In your module:
import { Module } from '@nestjs/common';

@Module({
  controllers: [AppController],
  providers: [GreetingService],
})
export class AppModule {}
Output
Hello from GreetingService!
🎯

When to Use

Use providers whenever you want to share logic or data across different parts of your NestJS app. Common examples include services that handle business logic, database repositories, or utility helpers.

For instance, if you have a service that fetches user data from a database, you make it a provider so controllers or other services can easily use it without rewriting code. This approach promotes reusability, easier testing, and cleaner code organization.

Key Points

  • Providers are the main way to share and organize code in NestJS.
  • They are classes or values that NestJS can inject where needed.
  • Use the @Injectable() decorator to mark a class as a provider.
  • Providers are registered in modules under the providers array.
  • Dependency Injection makes your code modular and testable.

Key Takeaways

A provider is a class or value that NestJS injects to share logic across your app.
Mark providers with @Injectable() and register them in a module's providers array.
Use providers to keep your code modular, reusable, and easy to test.
Dependency Injection automatically supplies providers where they are needed.
Controllers and other classes receive providers via constructor injection.