nestjsnestjs-confignestjs-fastify

NestJS Kafka Microservice with REST Endpoints


I am new to NestJS and was wondering if its possible to have a NestJS Kafka micro-service with REST Endpoints as well (ideally using Fastify).

I have found the following configuration for both Kafka and for Fastify but it seems like you can only have one or the other in the same service.

// kafka config

const app = await NestFactory.createMicroservice<MicroserviceOptions>(AppModule, {
    transport: Transport.KAFKA,
    options: {
      client: {
        brokers: ['localhost:9092'],
      },
    },
  });

// Fastify config

const app = await NestFactory.create<NestFastifyApplication>(AppModule, new FastifyAdapter(), {
    bufferLogs: true,
  });

Does anybody know if there is a way to configure both ?.


Solution

  • What you're looking for is called a hybrid application. First configure the HTTP engine:

    const app = await NestFactory.create<NestFastifyApplication>(AppModule, new FastifyAdapter(), {
     bufferLogs: true,
    });
    

    Then you use connectMicroservices:

    app.connectMicroservices<MicroserviceOptions>(AppModule, {
      transport: Transport.KAFKA,
      options: {
        client: {
          brokers: ['localhost:9092'],
        },
      },
    });
    

    then you call app.startAllMicroservices(), and finally you app.listen(port)