0
0
NestJSframework~5 mins

Hybrid applications in NestJS

Choose your learning style9 modes available
Introduction

Hybrid applications let you run both HTTP servers and microservices in one NestJS app. This saves time and keeps your code organized.

You want to build a web API and also listen to messages from a message queue in the same app.
You need to handle both REST requests and background jobs without separate apps.
You want to keep your app simple by combining different communication methods in one place.
Syntax
NestJS
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { MicroserviceOptions, Transport } from '@nestjs/microservices';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);

  app.connectMicroservice<MicroserviceOptions>({
    transport: Transport.TCP,
    options: { port: 8877 },
  });

  await app.startAllMicroservices();
  await app.listen(3000);
}

bootstrap();

You create a normal NestJS app with NestFactory.create().

Use connectMicroservice() to add microservice support.

Examples
This example connects a Redis microservice to the app.
NestJS
app.connectMicroservice({
  transport: Transport.REDIS,
  options: { url: 'redis://localhost:6379' },
});
This example connects a NATS microservice to the app.
NestJS
app.connectMicroservice({
  transport: Transport.NATS,
  options: { servers: ['nats://localhost:4222'] },
});
Sample Program

This app responds to HTTP GET requests with a greeting. It also listens as a TCP microservice for messages with command 'sum' and returns the sum of numbers.

NestJS
import { Controller, Get } from '@nestjs/common';
import { MessagePattern, Payload } from '@nestjs/microservices';
import { NestFactory } from '@nestjs/core';
import { Module } from '@nestjs/common';
import { MicroserviceOptions, Transport } from '@nestjs/microservices';

@Controller()
class AppController {
  @Get()
  getHello(): string {
    return 'Hello from HTTP!';
  }

  @MessagePattern({ cmd: 'sum' })
  sum(@Payload() data: number[]): number {
    return (data || []).reduce((a, b) => a + b, 0);
  }
}

@Module({
  controllers: [AppController],
})
class AppModule {}

async function bootstrap() {
  const app = await NestFactory.create(AppModule);

  app.connectMicroservice<MicroserviceOptions>({
    transport: Transport.TCP,
    options: { port: 8877 },
  });

  await app.startAllMicroservices();
  await app.listen(3000);
}

bootstrap();
OutputSuccess
Important Notes

Remember to start microservices with startAllMicroservices() before listening.

Hybrid apps let you reuse code and run multiple communication styles together.

Summary

Hybrid applications combine HTTP and microservices in one NestJS app.

Use connectMicroservice() to add microservice support.

This approach keeps your app simple and flexible.