Skip to content
Latchkey

NestJS "Cannot read properties of undefined" from a DI provider in CI

A method call failed because an injected dependency was undefined at the moment it was used. In Nest this usually means a circular dependency, a missing forwardRef, or accessing a dependency before construction finished.

What this error means

A request or test throws "TypeError: Cannot read properties of undefined (reading 'find')" from a service method, where the undefined value is an injected provider.

NestJS
TypeError: Cannot read properties of undefined (reading 'findOne')
    at CatsService.get (/app/dist/cats/cats.service.js:14:34)

Common causes

A circular dependency left the provider undefined

When two providers depend on each other without forwardRef, one is undefined when the other is constructed.

A dependency used before initialization

Accessing an injected provider in a field initializer or in the constructor body before Nest finishes wiring leaves it undefined.

How to fix it

Resolve the circular dependency

  1. Check whether the undefined provider is part of a cycle.
  2. Wrap both sides with forwardRef(() => Other).
  3. Or extract the shared logic to break the cycle.
cats.service.ts
constructor(
  @Inject(forwardRef(() => UsersService))
  private readonly users: UsersService,
) {}

Use dependencies after construction

Access injected providers inside methods or lifecycle hooks, not in field initializers that run before injection completes.

How to prevent it

  • Avoid provider cycles; use forwardRef only when unavoidable.
  • Do not use injected providers in field initializers.
  • Unit test services with a compiled TestingModule to catch undefined deps.

Related guides

Tired of flaky CI? Latchkey auto-heals failed jobs and retries them for you. Start free →