0
0
NestJSframework~5 mins

Optional providers in NestJS

Choose your learning style9 modes available
Introduction

Optional providers let you use a service only if it is available. This helps your app work even if some parts are missing.

You want to use a service only if it is registered in the app.
You build a module that can work with or without certain dependencies.
You want to avoid errors when a provider is not found.
You want to make your code more flexible and reusable.
Syntax
NestJS
constructor(@Optional() private readonly service?: ServiceType) {}
Use the @Optional() decorator before the provider in the constructor.
The provider will be undefined if it is not registered.
Examples
This example shows a service that uses an optional logger. If the logger is not provided, it won't cause errors.
NestJS
import { Optional, Injectable } from '@nestjs/common';

@Injectable()
export class MyService {
  constructor(@Optional() private readonly logger?: LoggerService) {}

  logMessage(msg: string) {
    this.logger?.log(msg);
  }
}
Here, the cacheService is optional. The service can work with or without it.
NestJS
constructor(@Optional() private readonly cacheService?: CacheService) {}
Sample Program

This example shows how MyService works with and without the LoggerService. When the logger is present, it logs a message. Otherwise, it prints a fallback message.

NestJS
import { Injectable, Optional } from '@nestjs/common';

@Injectable()
class LoggerService {
  log(message: string) {
    console.log('Log:', message);
  }
}

@Injectable()
class MyService {
  constructor(@Optional() private readonly logger?: LoggerService) {}

  doWork() {
    if (this.logger) {
      this.logger.log('Work started');
    } else {
      console.log('No logger available');
    }
  }
}

// Simulate NestJS container
const serviceWithLogger = new MyService(new LoggerService());
const serviceWithoutLogger = new MyService();

serviceWithLogger.doWork();
serviceWithoutLogger.doWork();
OutputSuccess
Important Notes

Always check if the optional provider exists before using it to avoid errors.

Optional providers help make your code more flexible and easier to test.

Summary

Use @Optional() to mark providers that may not be available.

Check if the provider exists before calling its methods.

Optional providers help your app handle missing dependencies gracefully.