#Publishing NestJS Middleware with ConfigService injected results in ConfigService Being undefined.

7 messages · Page 1 of 1 (latest)

lament sapphire
#

I have a package I'm publishing (to a private remote repo) where I have the below setup.

  • Configuration Class that has ConfigService injected.
  • NestJS Middleware Class that has above Configuration Class Injected
  • NestJS Module that exports both of the above and imports ConfigModule

When published and used in a NestJS Application, the Configuration Class is getting the ConfigService injected as undefined.

Has anyone perhaps done something similar with success?

dull jackal
#

Can you show the code of those files ?

lament sapphire
#
// Typesafe Config - logic etc. ommitted
import { ConfigService } from '@nestjs/config';
import { Injectable } from '@nestjs/common';

@Injectable()
export class AuthConfig extends AbstractBuilderNestjsConfig implements IAuthConfig {
  public issuer: URL;
  public constructor(private readonly configService: ConfigService) {
    this.issuer = this.configService.get('ISSUER');
  }
}
// Middleware - logic etc. omitted
import { Request, Response, NextFunction } from 'express';
import { Injectable, NestMiddleware } from '@nestjs/common';

@Injectable()
export class AuthMiddleware implements NestMiddleware {
  public constructor(private readonly config: AuthConfig) {}
  public use(req: Request, res: Response, next: NextFunction): void {
    ...
  }
}
// Module - as is
import { Module } from '@nestjs/common';
import { AuthConfig } from './auth.config';
import { AuthMiddleware } from './auth.middleware';
import { ConfigModule } from '@nestjs/config';

@Module({
  imports: [ConfigModule.forRoot()],
  providers: [AuthConfig, AuthMiddleware],
  exports: [AuthConfig, AuthMiddleware],
})
export class AuthModule {}
dull jackal
#

What is undefined in this example ?

lament sapphire
#

The ConfigService injected onto AuthConfig.

spark otter
#

Seems like nothing's wrong according to the code above, maybe the reason lies in other parts of your code, such as circular reference or something. If you want to implement an easy type-safe config service, maybe checkout https://github.com/Nikaple/nest-typed-config/, and try to simplify your own config service a bit.

lament sapphire
#

@spark otter thank you, I will give this a try hopefully today and report back. If no luck I'll get a couple sample repos going to see if I can reproduce 🤞.