{"record":{"id":"8960482df8897617","repo":"nestjs/nest","slug":"nest-can-t-resolve-dependencies-of-the-type-tost","errorCode":null,"errorMessage":"Nest can't resolve dependencies of the ${type.toString()}","messagePattern":"Nest can't resolve dependencies of the (.+?)","errorType":"exception","errorClass":"UndefinedDependencyException","httpStatus":null,"severity":"critical","filePath":"packages/core/injector/injector.ts","lineNumber":519,"sourceCode":"  }\n\n  public reflectSelfParams(type: Type<unknown> | Function): any[] {\n    return Reflect.getMetadata(SELF_DECLARED_DEPS_METADATA, type) || [];\n  }\n\n  public async resolveSingleParam<T>(\n    wrapper: InstanceWrapper<T>,\n    param: Type<any> | string | symbol,\n    dependencyContext: InjectorDependencyContext,\n    moduleRef: Module,\n    resolutionContext: ResolutionContext = { contextId: STATIC_CONTEXT },\n    keyOrIndex?: symbol | string | number,\n  ) {\n    if (isUndefined(param)) {\n      this.logger.log(\n        'Nest encountered an undefined dependency. This may be due to a circular import or a missing dependency declaration.',\n      );\n      throw new UndefinedDependencyException(\n        wrapper.name,\n        dependencyContext,\n        moduleRef,\n      );\n    }\n    const token = this.resolveParamToken(wrapper, param);\n    return this.resolveComponentWrapper(\n      moduleRef,\n      token,\n      dependencyContext,\n      wrapper,\n      resolutionContext,\n      keyOrIndex,\n    );\n  }\n\n  public resolveParamToken<T>(\n    wrapper: InstanceWrapper<T>,","sourceCodeStart":501,"sourceCodeEnd":537,"githubUrl":"https://github.com/nestjs/nest/blob/39fbddae51281ca56bf2fed9123d98e61509066c/packages/core/injector/injector.ts#L501-L537","documentation":"Thrown while the injector resolves constructor parameters: the resolved dependency token is `undefined`. NestJS reads constructor types from the `design:paramtypes` metadata that TypeScript emits (requires `emitDecoratorMetadata`); when that metadata contains `undefined` the class cannot be instantiated, so the container fails fast with UndefinedDependencyException instead of passing `undefined` into your constructor. In nearly all cases the `undefined` comes from the ES module system, not from your module configuration.","triggerScenarios":"resolveSingleParam is called with `param === undefined`: (1) two provider files import each other, so at decoration time the imported class binding is still `undefined`; (2) a provider is imported through a barrel file (index.ts) that participates in an import cycle; (3) `@Inject(TOKEN)` where the TOKEN constant is `undefined` when the decorator evaluates (again due to a cycle); (4) the parameter type is imported from a file whose exports are not yet initialized.","commonSituations":"Two services in different files reference each other's types; extracting classes into index.ts barrels during a refactor; introducing TypeScript path aliases that create cycles; importing a token constant from a file that also imports the consumer. Developers often see this right after adding a new cross-service dependency.","solutions":["Break the file-level circular import: move the shared types/interfaces to a third file that neither side depends on, or import one side directly instead of via a barrel.","If the classes genuinely need each other, use `@Inject(forwardRef(() => OtherService)) private readonly other: OtherService` on the injection side (and `moduleRef`/`forwardRef` in modules if needed).","Resolve the dependency lazily at runtime with `this.moduleRef.get(OtherService)` or `moduleRef.resolve()` inside a method instead of the constructor.","Confirm `\"emitDecoratorMetadata\": true` and `\"experimentalDecorators\": true` in tsconfig.json, especially after switching to esbuild/swc based builds that drop metadata by default.","Make sure the injected value is a concrete class or a real token, never an interface without `@Inject(token)`."],"exampleFix":"// before (files import each other -> design:paramtypes captures undefined)\n// a.service.ts\n@Injectable()\nexport class AService {\n  constructor(private readonly b: BService) {} // BService is undefined here\n}\n\n// after\nimport { Inject, forwardRef } from '@nestjs/common';\n\n@Injectable()\nexport class AService {\n  constructor(\n    @Inject(forwardRef(() => BService))\n    private readonly b: BService,\n  ) {}\n}","handlingStrategy":"validation","validationCode":"// Pre-bootstrap scan: no provider constructor may reference undefined tokens\nimport 'reflect-metadata';\n\nfunction assertNoUndefinedParams(classes: Function[]) {\n  for (const cls of classes) {\n    const params: any[] = Reflect.getOwnMetadata('design:paramtypes', cls) ?? [];\n    params.forEach((t, i) => {\n      if (t === undefined) {\n        throw new Error(\n          `${cls.name}: constructor param #${i} resolved to undefined — circular import or non-emitted type`,\n        );\n      }\n    });\n  }\n}\n// run before NestFactory.create(AppModule) with all provider classes","typeGuard":"const hasDefinedParamTypes = (cls: Function): cls is new (...args: any[]) => any =>\n  (Reflect.getOwnMetadata('design:paramtypes', cls) ?? []).every(t => t !== undefined);","tryCatchPattern":"try {\n  await NestFactory.create(AppModule);\n} catch (e: any) {\n  if (/can't resolve dependencies/i.test(String(e?.message))) {\n    console.error('DI wiring failure at bootstrap:', e.message);\n    process.exit(1);\n  }\n  throw e;\n}","preventionTips":["Keep \"emitDecoratorMetadata\": true and verify transpiler configs (swc/esbuild) that drop metadata silently.","Ban barrel-file re-exports of injectable classes or audit cycles with eslint-plugin-import (import/no-cycle).","Use @Inject(forwardRef(() => X)) at the first sign of a two-way dependency instead of waiting for runtime failure.","Never inject interfaces without an explicit @Inject(token); interfaces emit Object/undefined metadata."],"tags":["dependency-injection","circular-import","forwardref","typescript","bootstrap"],"backgroundTag":"circular-dependency","analyzedSha":"39fbddae51281ca56bf2fed9123d98e61509066c","analyzedAt":"2026-08-21T19:39:39.867Z","contentChangedAt":"2026-08-21T19:39:39.867Z","schemaVersion":2},"datasetVersion":"2026-09-14T00:17:10.932Z"}