📖 Scenario: You are building a simple NestJS application that needs to provide a greeting message. Instead of hardcoding the greeting, you want to use a custom provider to supply the greeting text. This approach helps keep your code flexible and easy to change later.
🎯 Goal: Build a NestJS module that uses a custom provider named GREETING to supply a greeting string. Then inject this provider into a service to return the greeting message.
📋 What You'll Learn
Create a custom provider named GREETING with the value 'Hello, NestJS!'
Create a service called GreetingService that injects the GREETING provider
Add a method getGreeting() in GreetingService that returns the injected greeting string
Register the custom provider and the service in a module called AppModule
💡 Why This Matters
🌍 Real World
Custom providers in NestJS allow you to inject values, classes, or factories that are not standard services. This is useful for configuration values, constants, or third-party libraries.
💼 Career
Understanding custom providers is essential for building scalable and maintainable NestJS applications, a skill often required for backend developer roles using Node.js and NestJS.
Progress0 / 4 steps
1
Create the custom provider with the greeting string
Create a constant called GREETING and set it to the string 'Hello, NestJS!'. Then create a provider object called greetingProvider with the key provide set to GREETING and useValue set to 'Hello, NestJS!'.
NestJS
Hint
Remember, a custom provider in NestJS is an object with provide and useValue keys.
2
Create the GreetingService that injects the custom provider
Create a class called GreetingService. Use the @Injectable() decorator. Add a constructor that injects the GREETING provider using @Inject(GREETING) and stores it in a private readonly variable called greeting.
NestJS
Hint
Use @Inject(GREETING) in the constructor parameter to inject the custom provider.
3
Add a method to return the greeting string
Inside the GreetingService class, add a method called getGreeting() that returns the private greeting string.
NestJS
Hint
The method should simply return the injected greeting string.
4
Register the provider and service in AppModule
Create a class called AppModule with the @Module() decorator. Inside the decorator, add providers array containing greetingProvider and GreetingService. Export the AppModule class.
NestJS
Hint
Use the @Module() decorator to register providers and services.
Practice
(1/5)
1. What is the main purpose of a custom provider in NestJS?
easy
A. To manage database connections automatically
B. To define routes for HTTP requests
C. To control how NestJS creates or finds a service or value
D. To handle user authentication and authorization
Solution
Step 1: Understand the role of providers in NestJS
Providers are responsible for creating and managing services or values that can be injected into other parts of the app.
Step 2: Identify what custom providers do
Custom providers let you control exactly how NestJS creates or finds these services or values, making your app more flexible.
Final Answer:
To control how NestJS creates or finds a service or value -> Option C
Quick Check:
Custom provider purpose = control creation/finding [OK]
Hint: Custom providers control service creation or retrieval [OK]
Common Mistakes:
Confusing providers with routing or middleware
Thinking providers manage database or auth directly
Assuming providers only register classes, not values or factories
2. Which of the following is the correct syntax to provide a custom value provider in a NestJS module?
easy
A. { provide: 'API_URL', useValue: 'https://api.example.com' }
B. { provide: 'API_URL', useClass: 'https://api.example.com' }
C. { provide: 'API_URL', useFactory: 'https://api.example.com' }
D. { provide: 'API_URL', useExisting: 'https://api.example.com' }
Solution
Step 1: Recall the syntax for value providers
Value providers use the useValue key to assign a fixed value to a token.
Step 2: Check each option's correctness
{ provide: 'API_URL', useValue: 'https://api.example.com' } correctly uses useValue with a string value. Other options misuse useClass, useFactory, or useExisting which expect different types.
Final Answer:
{ provide: 'API_URL', useValue: 'https://api.example.com' } -> Option A
Hint: Always register providers in module's providers array [OK]
Common Mistakes:
Assuming useFactory must be async
Thinking tokens must be classes only
Believing useFactory can't return objects
5. You want to create a custom provider that returns different database connection strings based on environment variables. Which approach correctly implements this using a factory provider in NestJS?
To choose a value based on environment variables at runtime, a factory provider is ideal because it runs code to decide the value.
Step 2: Evaluate each option
{ provide: 'DB_CONNECTION', useFactory: () => process.env.NODE_ENV === 'prod' ? 'prod-db' : 'dev-db' } uses useFactory with a function that returns the correct string based on process.env.NODE_ENV. { provide: 'DB_CONNECTION', useValue: process.env.NODE_ENV === 'prod' ? 'prod-db' : 'dev-db' } uses useValue which is static at module load time. Options C and D misuse useClass and useExisting with strings or conditions incorrectly.