Search code examples
dependency-injectionnestjsnest-dynamic-modules

Why can't NestJS resolve the dynamic module options parameter I added as a provider?


I made a dynamic module named AuthModule copied from Nest's documentation. I changed it so I could supply different Auth0 tenant credentials to the Auth0Service for every module that imports it. The configuration parameter in the provider array of the Auth. module is unresolved in the importing/calling module. The error appears when I run npm run start. I called Auth0's register method in the calling module (Users) imports array. I have added Auth's options parameter to its array of providers. When I run npm start, I get an error saying Nest cannot resolve the dependency AUTH0_CONFIG.

Nest can't resolve dependencies of the Auth0Service (?)...Please make sure that the argument AUTH0_CONFIG at index [0] is available in the UsersModule context.

Exporting the options parameter from Auth0 allows my app to run. The problem is that when I make any Axios request in the Auth0Service thru UsersModule, I get a 409 error. I get the 409 error even from Auth0 API endpoints that do not return a 409 error according to Auth0 documentation.

The Auth0 module is globally scoped and imported by UsersModule. Auth0's register method returns itself dynamic module:

@Global()
@Module({})
export class AuthModule {
  public static register(auth0Params: Auth0Params): DynamicModule {
    return {
      module: AuthModule,
      providers: [
        { provide: AUTH0_CONFIG, useValue: auth0Params },
        Auth0Service,
      ],
      exports: [AuthService],
    };
  }
}

This is how I imported the AuthModule into UsersModule:

@Module({
  imports: [
    TypeOrmModule.forFeature([User, UserRepository]),
    HttpModule,
    AuthModule.register({
      domain: process.env.DOMAIN,
      clientId: process.env.CLIENT_ID,
      clientSecret: process.env.CLIENT_SECRET,
    }),
  ],
  providers: [UserService, UserResolver, Auth0Service],
  exports: [UserService],
})
export class UserModule {}

How do I solve this? What should I check?


Solution

  • as you're importing the dynamic module AuthModule.register into UserModule, which exports the provider Auth0Service, I don't see any reason to register that provider again in UserModule.

    When you do so, you must have to register all the dependencies of Auth0Service again into UserModule, but you can't do that as that AUTH0_CONFIG is private to AuthModule.

    To solve this, just drop the Auth0Service from providers array of UserModule.

    When we import some module, we're importing all the providers that that module registers and exports.