Skip to content

Nest Microservices: Custom strategy injection fails when using dynamic configuration (useFactory) #15144

@Stormix

Description

@Stormix

Is there an existing issue for this?

  • I have searched the existing issues

Current behavior

When using dynamic configuration to create a microservice with useFactory, the current implementation of createServer in NestJS does not properly support custom strategies. It assumes that dynamic configuration will only be used with built-in transport strategies (e.g., Transport.TCP) and does not check for a strategy field in the resolved options.

Code causing the issue:

public createServer(config: CompleteMicroserviceOptions) {
  try {
    if ('useFactory' in config) {
      this.microserviceConfig = this.resolveAsyncOptions(config);
    } else {
      this.microserviceConfig = {
        transport: Transport.TCP,
        ...config,
      } as MicroserviceOptions;
    }

    if ('strategy' in config) { // This should also check for a strategy in the async options.
      this.serverInstance = config.strategy as Server;
      return;
    } else {
      this.serverInstance = ServerFactory.create(
        this.microserviceConfig,
      ) as Server;
    }
  } catch (e) {
    this.logger.error(e);
    throw e;
  }
}

Relevant Docs:

Minimum reproduction code

https://stackblitz.com/edit/nestjs-typescript-starter-mndepscp?file=src%2Fcustom.ts

Steps to reproduce

  1. Attempt to create a microservice with a custom strategy using dynamic configuration:
const app = await NestFactory.createMicroservice<AsyncMicroserviceOptions>(
  AppModule,
  {
    useFactory: (configService: ConfigService) => ({
      strategy: new CustomStrategy(configService.get('HOST')), // Custom logic
    }),
    inject: [ConfigService],
  },
);
  1. The strategy is ignored because it is not checked after resolving the config.

Expected behavior

After resolving the async config via useFactory, the framework should check if the resulting config includes a strategy and use it accordingly, just like it does for static configurations.

Package

  • I don't know. Or some 3rd-party package
  • @nestjs/common
  • @nestjs/core
  • @nestjs/microservices
  • @nestjs/platform-express
  • @nestjs/platform-fastify
  • @nestjs/platform-socket.io
  • @nestjs/platform-ws
  • @nestjs/testing
  • @nestjs/websockets
  • Other (see below)

Other package

No response

NestJS version

^11.0.1

Packages versions

"@nestjs/common": "^11.0.1",
"@nestjs/config": "^4.0.2",
"@nestjs/core": "^11.0.1",
"@nestjs/microservices": "^11.1.1",
"@nestjs/platform-express": "^11.0.1",

Node.js version

22.13.0

In which operating systems have you tested?

  • macOS
  • Windows
  • Linux

Other

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions