How to Fix Unknown Dependencies Error in NestJS
unknown dependencies error in NestJS happens when a provider is not registered or imported correctly in the module. To fix it, ensure the service or provider is added to the providers array and imported in the module where it is used.Why This Happens
This error occurs because NestJS cannot find the provider (service, repository, or other injectable) you want to use. It usually means you forgot to add the provider to the providers array of the module or forgot to import the module that exports it.
import { Injectable } from '@nestjs/common'; @Injectable() export class CatsService { getCats() { return ['Tom', 'Jerry']; } } import { Controller, Get } from '@nestjs/common'; @Controller('cats') export class CatsController { constructor(private catsService: CatsService) {} @Get() findAll() { return this.catsService.getCats(); } } import { Module } from '@nestjs/common'; @Module({ controllers: [CatsController], // providers: [CatsService], // Missing this line causes unknown dependency error }) export class CatsModule {}
The Fix
To fix the error, add the missing provider to the providers array in the module. If the provider is in another module, import that module and export the provider there.
import { Injectable } from '@nestjs/common'; @Injectable() export class CatsService { getCats() { return ['Tom', 'Jerry']; } } import { Controller, Get } from '@nestjs/common'; @Controller('cats') export class CatsController { constructor(private catsService: CatsService) {} @Get() findAll() { return this.catsService.getCats(); } } import { Module } from '@nestjs/common'; @Module({ controllers: [CatsController], providers: [CatsService], }) export class CatsModule {}
Prevention
Always register your services and providers in the module's providers array. If you use a provider from another module, import that module and export the provider there. Use NestJS CLI to generate modules and services to avoid missing registrations. Enable strict linting rules to catch missing providers early.
Related Errors
Other common errors include:
- "Nest can't resolve dependencies of the X": Usually means a missing provider or circular dependency.
- Circular dependency error: Happens when two providers depend on each other; fix by using
@Inject(forwardRef(() => OtherService)). - Provider not found in module: Ensure the provider is exported from its module and the module is imported where needed.