0
0
NestJSframework~5 mins

Health checks (Terminus) in NestJS

Choose your learning style9 modes available
Introduction

Health checks help your app tell if it is working well. Terminus makes it easy to add these checks in NestJS.

You want to know if your NestJS app is running fine.
You need to check if your database or other services are connected.
You want to let monitoring tools see your app's health automatically.
You want to restart or fix your app if it stops working properly.
Syntax
NestJS
import { Module, Controller, Get } from '@nestjs/common';
import { TerminusModule } from '@nestjs/terminus';
import { HealthCheckService, HttpHealthIndicator } from '@nestjs/terminus';

@Controller('health')
export class HealthController {
  constructor(
    private health: HealthCheckService,
    private http: HttpHealthIndicator,
  ) {}

  @Get()
  check() {
    return this.health.check([
      () => this.http.pingCheck('nestjs-docs', 'https://docs.nestjs.com'),
    ]);
  }
}

@Module({
  imports: [TerminusModule],
  controllers: [HealthController],
  providers: [HealthCheckService, HttpHealthIndicator],
})
export class AppModule {}

Use TerminusModule to enable health checks in your app.

Health checks are functions that return if a part of your app is healthy.

Examples
Check if Google website is reachable.
NestJS
return this.health.check([
  () => this.http.pingCheck('google', 'https://google.com'),
]);
Check if your database connection is alive.
NestJS
return this.health.check([
  () => this.db.pingCheck('database'),
]);
Custom health check using your own service logic.
NestJS
@Get('custom')
checkCustom() {
  return this.health.check([
    async () => ({
      customService: await this.customService.isHealthy(),
    }),
  ]);
}
Sample Program

This NestJS app has a health endpoint at /health. It checks if the NestJS docs website is reachable. If yes, it returns a healthy status.

NestJS
import { Module, Controller, Get } from '@nestjs/common';
import { TerminusModule, HealthCheckService, HttpHealthIndicator } from '@nestjs/terminus';

@Controller('health')
export class HealthController {
  constructor(
    private health: HealthCheckService,
    private http: HttpHealthIndicator,
  ) {}

  @Get()
  check() {
    return this.health.check([
      () => this.http.pingCheck('nestjs-docs', 'https://docs.nestjs.com'),
    ]);
  }
}

@Module({
  imports: [TerminusModule],
  controllers: [HealthController],
  providers: [HealthCheckService, HttpHealthIndicator],
})
export class AppModule {}
OutputSuccess
Important Notes

Health checks should be fast and not block your app.

You can add many checks for databases, APIs, or custom services.

Use the @Get() route to expose the health check URL.

Summary

Terminus helps add health checks in NestJS easily.

Health checks tell if your app and its parts are working well.

Use HealthCheckService and indicators like HttpHealthIndicator to create checks.