Skip to content

NestMicroservice

reference
2 min readUpdated

Kind: Class

Source: packages/microservices/nest-microservice.ts

Part of: Microservices

NestMicroservice is the runtime application class used to bootstrap and manage a NestJS microservice transport server. It creates the server, registers modules and message listeners, applies global enhancers, and coordinates the init() and listen() lifecycle stages.

Extends: NestApplicationContext

Implements: INestMicroservice

Methods

MethodSignatureReturns
createServercreateServer(config: CompleteMicroserviceOptions)void
registerModulesregisterModules()Promise<any>
registerListenersregisterListeners()void
useWebSocketAdapteruseWebSocketAdapter(adapter: WebSocketAdapter)this
useGlobalFiltersuseGlobalFilters(filters: ExceptionFilter[])this
useGlobalPipesuseGlobalPipes(pipes: PipeTransform<any>[])this
useGlobalInterceptorsuseGlobalInterceptors(interceptors: NestInterceptor[])this
useGlobalGuardsuseGlobalGuards(guards: CanActivate[])this
initinit()Promise<this>
listenlisten()Promise<any>
closeclose()Promise<any>
setIsInitializedsetIsInitialized(isInitialized: boolean)void
setIsTerminatedsetIsTerminated(isTerminated: boolean)void
setIsInitHookCalledsetIsInitHookCalled(isInitHookCalled: boolean)void
on`on(event: stringnumber
unwrapunwrap()T
closeApplicationcloseApplication()Promise<any>
disposedispose()Promise<void>
resolveAsyncOptionsresolveAsyncOptions(config: AsyncMicroserviceOptions)void

Properties

PropertyType
loggerany

Where it refuses work

  • NestMicroservice stops the work with an early return when this.isTerminated, in 2 places.
  • NestMicroservice stops the work with an early return when this.isInitialized.
  • NestMicroservice stops the work with an early return when err.
  • NestMicroservice stops the work with an early return when 'on' in this.serverInstance.
  • NestMicroservice stops the work with an early return when 'unwrap' in this.serverInstance.
  • NestMicroservice stops the work with an early return when this.appOptions.instrument?.instanceDecorator.

When something fails

  • NestMicroservice handles failure in 1 place: it lets it reach the caller in all 1.

Diagram

mermaid
graph LR
  A[NestFactory.createMicroservice] --> B[NestMicroservice]
  B --> C[createServer]
  B --> D[registerModules]
  D --> E[registerListeners]
  B --> F[Global Pipes / Guards / Filters / Interceptors]
  B --> G[init]
  G --> H[listen]
  H --> I[Transport Server]
  I --> J[Message Handlers]

Usage

ts
import { ValidationPipe } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { Transport } from '@nestjs/microservices';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.createMicroservice(AppModule, {
    transport: Transport.TCP,
    options: {
      host: '127.0.0.1',
      port: 3001,
    },
  });

  app.useGlobalPipes(
    new ValidationPipe({
      transform: true,
      whitelist: true,
    }),
  );

  await app.listen();
}

bootstrap();

AI Coding Instructions

  • Prefer creating microservices through NestFactory.createMicroservice() rather than instantiating NestMicroservice directly.
  • Configure transport options before calling listen(), since server creation and listener registration depend on the selected transport.
  • Register global pipes, guards, interceptors, and filters during application setup, before the microservice begins listening.
  • Preserve the lifecycle order: create server, register modules and handlers, initialize the application, then start listening.
  • Ensure controllers use microservice message-pattern decorators such as @MessagePattern() so registerListeners() can bind handlers to the transport.

Relationships

  • IMPORTS → CanActivate
  • IMPORTS → ExceptionFilter
  • IMPORTS → INestMicroservice
  • IMPORTS → NestInterceptor
  • IMPORTS → PipeTransform
  • IMPORTS → WebSocketAdapter
  • IMPORTS → NestMicroserviceOptions
  • IMPORTS → Logger
  • IMPORTS → ApplicationConfig
  • IMPORTS → MESSAGES
  • IMPORTS → optionalRequire
  • IMPORTS → NestContainer
  • IMPORTS → Injector
  • IMPORTS → GraphInspector
  • IMPORTS → NestApplicationContext
  • IMPORTS → SocketModule

Was this page helpful?

Download as PDF
NestMicroservice — NestJS head-to-head