Health checks

Checking if the system is healthy.

We may use Terminus to check the health of our components. It offers a set of health indicators, in order to confirm the overall health of the system. Let's then check the database health.

First, we should install the necessary dependency.

yarn add @nestjs/terminus

Now, create a resource for health with no CRUD, and inside the module import the TerminusModule.

nest g res health

In the controller, create a route for performing the health check. We may restrict it to an admin.

@Roles(Role.ADMIN)
@HealthCheck()
@Get()
check() {
  return this.healthService.check();
}

Note the @HealthCheck() decorator, which will make this route:

  • Be documented by Swagger

  • Not be cached

Then, in the service, inject the HealthCheckService and the TypeOrmHealthIndicator.

private readonly health: HealthCheckService,
private readonly database: TypeOrmHealthIndicator,

Finally, we should use the HealthCheckService to determine the overall health, passing to it all the indicators we want. In this case, it will be just the database indicator.

If you want to add more indicators, this NestJS doc shows all the available options, and examples of how to use some of them.

Commit - Adding health check

Last updated